XML Parser通过比较其值来获取特定属性

时间:2012-04-11 08:52:13

标签: java xml parsing

我有XML文件内容,如下所示。

<FileIndex>
<Document SEQUENCE="0" FILENAME="A.xml"  />
<Document SEQUENCE="1" FILENAME="B.htm"  />
<Document SEQUENCE="2" FILENAME="C.htm"  />
<Document SEQUENCE="3" FILENAME="D.htm"  />

我想得到属性FILENAME的值,其中属性SEQUENCE的值为equls为“1”。哪个是首选方式? SAX,DOM,XPath?以及如何实施它?

1 个答案:

答案 0 :(得分:1)

以下是您的需求:

  @Test
  public void test() throws Exception
  {
    String xml =
        "<FileIndex>\n" + 
        "<Document SEQUENCE=\"0\" FILENAME=\"A.xml\"  />\n" + 
        "<Document SEQUENCE=\"1\" FILENAME=\"B.htm\"  />\n" + 
        "<Document SEQUENCE=\"2\" FILENAME=\"C.htm\"  />\n" + 
        "<Document SEQUENCE=\"3\" FILENAME=\"D.htm\"  />\n" + 
        "</FileIndex>";
    XPath xp = XPathFactory.newInstance().newXPath();
    System.out.println(xp.evaluate("/FileIndex/Document[@SEQUENCE='1']/@FILENAME", new InputSource(new StringReader(xml)), XPathConstants.STRING));
  }

对于这样的小型XML,最好使用XPath