2

我正在使用 SAX Parser 解析 xml。当我需要获取的数据是 xml 标记的主体时,一切工作正常。我得到的唯一问题是当我需要的数据是那个 XML 标记的属性值时。我如何获得这个属性值?

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

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

我正在使用的代码是:

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

1 回答 1

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"));
    }   
} 
于 2011-07-06T10:03:15.047 回答