XML Parsing to get Attribute Value

那年仲夏 提交于 2019-12-06 10:55:10

问题


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
    }
}

回答1:


@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"));
    }   
} 


来源:https://stackoverflow.com/questions/6594184/xml-parsing-to-get-attribute-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!