本示例说明如何使用SAX解析器获取XML文件中元素的属性。
package org.nhooo.example.xml;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.InputStream;
public class SAXElementAttribute {
public static void main(String[] args) {
SAXElementAttribute demo = new SAXElementAttribute();
demo.run();
}
private void run() {
try {
// 创建SAXParserFactory实例和一个SAXParser
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
// 获取InputStream到elements.xml文件并进行解析
// 其内容使用SAXHandler。
InputStream is =
getClass().getResourceAsStream("/elements.xml");
DefaultHandler handler = new SAXHandler();
parser.parse(is, handler);
} catch (Exception e) {
e.printStackTrace();
}
}
class SAXHandler extends DefaultHandler {
@Override
public void startElement(String uri, String localName,
String qName, Attributes attributes)
throws SAXException {
int attributeLength = attributes.getLength();
if ("person".equals(qName)) {
for (int i = 0; i < attributeLength; i++) {
// 获取属性名称和值
String attrName = attributes.getQName(i);
String attrVal = attributes.getValue(i);
System.out.print(attrName + " = " + attrVal + "; ");
}
System.out.println("");
}
}
}
}该elements.xml文件如下:
<?xml version="1.0" encoding="UTF-8"?> <root> <persons> <person name="Foo" age="25"/> <person name="Bar" age="22"/> </persons> </root>