hades
hades

Reputation: 4696

Java SAX parse XML file

I have one xml file to process, but the xml file is not in conventional xml format, normally xml have the following format, then i can use java's SAXParser to extract the info:

<Info>
<Product id>123456</Product id>
<code2>985632</code2>
<code3>896523</code3>
<Product id>123343</Product id>
<code2>935632</code2>
<code3>856523</code3>
</Info>

But now my xml is in this form, i cant use the SAXParser technique to search for start-tag, and end-tag. Any idea please?

<Info>
<Product id="123456" code2="985632" code3="896523" />
<Product id="123343" code2="935632" code3="856523" />
...
</Info>

Normally java SAX parser use the following methods to detect xml's start tag, xml's eng tag, and xml's content, but since my xml dont even have proper end tag, i not sure whether i can use java SAX parser or not.

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

}

public void endElement(String uri, String localName, String qName)
throws SAXException {
}

public void characters(char ch[], int start, int length)
throws SAXException {
}

Upvotes: 0

Views: 167

Answers (1)

ihsan
ihsan

Reputation: 586

You will have to get the attributes of those tags by doing something like this:

@Override
public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {

    int length = attributes.getLength();

    for(int i=0; i<length; i++) {

            // Qualified name by index
            String name = attributes.getQName(i);

            // Attribute value by index
            String value = attributes.getValue(i);

            // Namespace URI by index
            String nsUri = attributes.getURI(i);

            // Local name by index
            String lName = attributes.getLocalName(i);
        }
    }

This will get all the attributes in the tag by the index.

Source

Upvotes: 1

Related Questions