假设我得到了一个XML文件,其中im SAX解析(到Java)的格式如下:
<RootElement>
<text> blabla </text>
<rule1 name="a">1</rule1>
<rule2 name="b">2</rule2>
</RootElement>我如何在每条规则中引用名称的属性?我的目标是将名为"a“的规则保存到txt文件中。谢谢
发布于 2013-08-04 16:32:11
当您使用SAX读取XML时,您实现了一种ContentHandler (参见http://docs.oracle.com/javase/7/docs/api/org/xml/sax/ContentHandler.html)。在ContentHandler中,当解析器输入"rule1“和"rule2”时,将调用startElement方法。startElement的一个参数是属性,它基本上是对应值的属性名映射(在示例中是“name”)。
一些代码片段看起来应该是:
// Handle XML SAX parser events.
private ContentHandler contentHandler = new ContentHandler() {
public void startDocument() throws SAXException {...}
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
cdata.setLength(0);
if(atts == null) return;
// Write out attributes as new rows
for(int i = 0; i < atts.getLength(); i++) {
System.out.println(atts.getLocalName(i) + ": " + atts.getValue(i));
}
}
public void characters(char[] ch, int start, int length) throws SAXException {...}
public void endElement(String uri, String localName, String qName) throws SAXException {...}
// All other events are ignored
public void endDocument() throws SAXException {}
public void endPrefixMapping(String prefix) throws SAXException {}
public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {}
public void processingInstruction(String target, String data) throws SAXException {}
public void setDocumentLocator(Locator locator) {}
public void skippedEntity(String name) throws SAXException {}
public void startPrefixMapping(String prefix, String uri) throws SAXException {}
};发布于 2013-08-04 16:33:28
如果使用SAX解析XML,则可以在startElement()实现的重写的ContentHandler方法中(通过扩展DefaultHandler)检查元素的属性值。
public class MySAXHandler extends DefaultHandler {
// ...
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
// .. other elements ..
// process <rule1,2 etc.
if (localName.startsWith("rule")) {
String value = attributes.getValue("name");
if (value != null && value.equals("a")) {
// save this rule
}
}
}
}参考
https://stackoverflow.com/questions/18044675
复制相似问题