XML解析获取属性值

时间:2011-07-06 09:25:50

标签: android saxparser getattr

我使用SAX Parser解析xml。当我需要获取的数据是xml标记的主体时,Everythings工作得很好。我得到的唯一问题是我需要的数据是该XML标签的属性值。我如何获得此属性值?

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

假设这是一个标签,我可以获得Body而不是值

我正在使用的代码是:

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 个答案:

答案 0 :(得分: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"));
    }   
}