在Java中使用XPath获取XML文件的所有属性
我正在解析一个复杂的XML文件,我希望使用Java中的XPath从整个文档中获取所有属性及其值。问题是文档在树的结构中包含许多嵌套的标记,因此很难实现。如果有另一种更简单的方法在Java中实现这一点,那也会很有帮助。我已经尝试过DOM,但是多重嵌套使得这种方法很难实现 举个例子,如果我有这个:在Java中使用XPath获取XML文件的所有属性,java,xml,xpath,xml-parsing,sax,Java,Xml,Xpath,Xml Parsing,Sax,我正在解析一个复杂的XML文件,我希望使用Java中的XPath从整个文档中获取所有属性及其值。问题是文档在树的结构中包含许多嵌套的标记,因此很难实现。如果有另一种更简单的方法在Java中实现这一点,那也会很有帮助。我已经尝试过DOM,但是多重嵌套使得这种方法很难实现 举个例子,如果我有这个: <bookstore> <book category="COOKING"> <title lang="en">Everyday Italian</title
<bookstore>
<book category="COOKING">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="CHILDREN">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="WEB">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>
<book category="WEB">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
多谢各位 如果您不关心嵌套结构(即,您只需要一个属性列表),则可以直接使用它 例如,您可以将
DefaultHandler
子类化,覆盖startElement
方法以从每个标记收集属性:
class GetAttributesHandler extends DefaultHandler {
List<Attributes> attributes = new ArrayList<>();
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) {
this.attributes.add(attributes);
}
}
类getAttributeHandler扩展了DefaultHandler{
列表属性=新的ArrayList();
@凌驾
public void startElement(字符串uri、字符串localName、字符串qName、属性){
this.attributes.add(属性);
}
}
class GetAttributesHandler extends DefaultHandler {
List<Attributes> attributes = new ArrayList<>();
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) {
this.attributes.add(attributes);
}
}