2
我正在使用SAX解析器解析xml。當我需要得到的數據是XML標籤的主體時,所有東西都能正常工作。我遇到的唯一問題是何時需要的數據是該XML標記的屬性值。我如何得到這個屬性值?XML解析以獲取屬性值
<xml att="value"> Body </xml>
假設這是一個標籤,我能得到身體,但不珍惜我使用
代碼:
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
}
}
感謝很多:) – Gaurav
你讓我一天:) –
@fernando Miguelez我有同樣的問題,但我使用XMLParser而不是SAXParser,你能給我一個解決方法嗎? –