2

I am parsing a xml using SAX Parser. Everythings working fine when the data I need to get is the body of a xml tag. The only problem I am getting is when the data I need is the attribute value of that XML tag. How do i get this attribute value?

<xml att="value"> Body </xml>

Suppose this is a tag, I am able to get Body but not value

code I am using is:

URL url = new URL("http://example.com/example.xml");

SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();

XMLReader xr = sp.getXMLReader();
ExampleHandler myExampleHandler = new ExampleHandler();
xr.setContentHandler(myExampleHandler);

xr.parse(new InputSource(url.openStream()));

public class ExampleHandler extends DefaultHandler { 
String buff = new String("");
boolean buffering = false; 

@Override
public void startDocument() throws SAXException {
    // Some sort of setting up work
} 

@Override
public void endDocument() throws SAXException {
    // Some sort of finishing up work
} 

@Override
public void startElement(String namespaceURI, String localName, String qName, 
        Attributes atts) throws SAXException {
    if (localName.equals("qwerasdf")) {
        buff = new String("");
        buffering = true;
    }   
} 

@Override
public void characters(char ch[], int start, int length) {
    if(buffering) {
        buff=new String(ch, start, length)
    }
} 

@Override
public void endElement(String namespaceURI, String localName, String qName) 
throws SAXException {
    if (localName.equals("blah")) {
        buffering = false; 
        String content = buff.toString();

        // Do something with the full text content that we've just parsed
    }
}
Hussain
  • 5,552
  • 4
  • 40
  • 50
Gaurav
  • 1,700
  • 4
  • 22
  • 38

1 Answers1

8
@Override
public void startElement(String namespaceURI, String localName, String qName, 
        Attributes atts) throws SAXException {
    if (localName.equals("xml")) {
          System.out.println("The value of attribute 'att' is: " + atts.getValue("att"));
    }   
} 
Fernando Miguélez
  • 11,196
  • 6
  • 36
  • 54
  • @fernando Miguelez I have the same problem but I'm using XMLParser instead of SAXParser, can you give me a workaround for that too? – Abdus Sami Khan May 26 '13 at 16:47
  • XMLParser is the class of the SAX API, and SAXParser is the SAX parser of the JAXP API (I prefer the latter method, which is more standard). Both should have similar methods. – Fernando Miguélez May 27 '13 at 06:47