开发者

XML parsing in java [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in 开发者_JAVA百科its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

Using SAX parser in Java, how to do attribute based parsing.

Suppose my xml file is as follows,

 <?xml version="1.0" encoding="UTF-8"?>
<employees category="1" type="regular" location="india">
    <employee name="xyz" doj="20/12/2001" dob="21/12/1988" salary="12000"></employee>
    <employee name="xyz" doj="22/12/2003" dob="22/12/1988" salary="18000"></employee>
    <employee name="xyz" doj="23/12/2002" dob="23/12/1988" salary="15000"></employee>
    <employee name="xyz" doj="24/12/2003" dob="22/12/1988" salary="17000"></employee>
    <employee name="xyz" doj="26/12/2005" dob="24/12/1988" salary="12000"></employee>

</employees>

I want to fetch the each attribute values of employee element. Please help me out


The DefaultHandler class provides a callback to listen for start elements, and it has a signature that contains an Attributes object, representing the attributes of that element.

startElement(String uri, String localName, String qName, Attributes attributes)

Looking at the Attributes interface, I see methods to help you out.

  1. If you don't know which attributes you are interested in, and you want to look at all attributes, you should use getLength(), and the do a for-loop over that length, looking at each attributes getLocalName(int) or getQName(int), and you can find its value by calling getValue(int) (all int's are used as indices into the attributes list).
  2. If you do know which attributes you are interested in, you can simply call getValue(String), passing in the string name of the attribute you are after.

Here is some example code that could get you the names and values of all attributes of a given element:

public void startElement(String ns, String localName, String qName, Attributes attrs) throws SAXException {
    for(int i = 0; i < attrs.getLength(); ++i) {
        String attrName = attrs.getLocalName(i);
        String attrValue = attrs.getValue(i);

        //do stuff with name/value
    }
}


SAX programming can be very confusing if you're not used to it. Constructing the parser is a bit tricky because you have to struggle with the abstract Interface API. Once you get it all going and register your handler though, accessing the attributes should be straightforward; your handler class need to implement the method:

public void startElement(String nsUri, String localName, String qName, Attributes attributes) 
        throws SAXException            

The attribute values are available in the arg of that name.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜