使用Java中的XPath获取XML文件的所有属性

时间:2015-08-18 21:11:34

标签: java xml xpath xml-parsing sax

我正在解析一个复杂的XML文件,我希望使用Java中的XPath从整个文档中获取所有属性及其值。问题是文档在树的结构中包含许多嵌套标记,因此很难。如果在Java中有另一种更简单的方法可以提供帮助。我已经尝试过DOM,但多重嵌套使得这种方法很难实现。

例如,如果我有这个:

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

我想要这个:

category : COOKING
lang : en
category : CHILDREN
lang : en
category : WEB
lang : en
category : WEB
lang : en

谢谢。

1 个答案:

答案 0 :(得分:0)

如果您不关心嵌套结构(即您只需要一个属性列表),则可以直接使用SAX

例如,您可以继承DefaultHandler,重写startElement方法以从每个标记中收集Attributes

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);
  }
}