从Java中的xml获取特定属性值

时间:2016-06-16 06:16:32

标签: java xml parsing

我正在尝试使用Java解析以下XML。

    <connection inherit="true" name="test">
      <ConnectionDetails>
        <conn name="domainname1.net">
            <prop name="dom-test" tags="1-test, con"/>
        </conn>
        <conn name="domainname2.net">
            <prop name="dom-test" tags="2-test, con"/>
        </conn>
        <conn name="domainname3.net">
            <prop name="dom-org" tags="org, con"/>
        </conn>
        <conn name="domainname4.net">
            <prop name="dom-test" tags="3-test"/>
        </conn>
        <conn name="domainname5.net">
           <prop name="dom-org" tags="org"/>
        </conn>
      </ConnectionDetails>
 </connection>

我编写了如下代码的Java代码:

File inputFile = new File("test.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(inputFile);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("conn");

我需要的是:

  
      
  • 获取包含文本“test”的标记的所有连接         - domainname1.net,domainname2.net,domainname4.net
  •   

请帮忙!

1 个答案:

答案 0 :(得分:1)

您可以使用XPath:

XPath xPath = XPathFactory.newInstance().newXPath();
XPathExpression query = xPath.compile("//prop[contains(@tags, 'test')]/../@name");
NodeList nList = (NodeList)query.evaluate(doc, XPathConstants.NODESET);

如果您更喜欢更手动的方法(或者您不想要XPath的开销),您可以这样做:

NodeList nList = doc.getElementsByTagName("prop");
for (int i = 0, len = nList.getLength(); i < len; i++) {
    Element elm = (Element)nList.item(i);
    if (elm.getAttribute("name").contains("test")) {
        String connName = ((Element)elm.getParentNode()).getAttribute("name");
        // ...
    }
}