我想根据属性值选择一个注释节点

时间:2012-05-17 09:44:28

标签: java xml xpath

XML NODE

 <!-- url path="/jsp/Admin_BetaSignup.jsp" roles="ZohoCampaignAdmin" authentication="optional" description="Page used to add the Beta users">
        <param name="zuid" xss="throwerror" max-len="300"/>
</url -->

我想通过xpath选择此节点。我在java中使用下面的代码。

Document document = DocumentBuilderFactory.newInstance()
    .newDocumentBuilder()
    .parse("/home/local/ZOHOCORP/bharathi-1397/build/AdventNet/Sas/webapps/zcadmin/WEB-INF/security.xml");
XPath xpath = XPathFactory.newInstance().newXPath();
System.out.println(
    xpath.evaluate("//comment()[@path='/jsp/Admin_BetaSignup.jsp']",
    document,XPathConstants.NODE)
);

输出:null。

为什么?

2 个答案:

答案 0 :(得分:3)

Comment不是元素节点,它不包含属性。因此,您必须获取所有注释节点,然后解析它们。

答案 1 :(得分:1)

使用

//comment()[contains(., 'path="/jsp/Admin_BetaSignup.jsp"')]

基于XSLT的验证

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:template match="/">
     <xsl:copy-of select=
     "//comment()
         [contains(., 'path=&quot;/jsp/Admin_BetaSignup.jsp&quot;')]
    "/>
 </xsl:template>
</xsl:stylesheet>

在以下XML文档中应用此转换时:

<!-- url path="/jsp/Admin_BetaSignup.jsp" roles="ZohoCampaignAdmin" authentication="optional" description="Page used to add the Beta users">         <param name="zuid" xss="throwerror" max-len="300"/> </url -->
<t>
 <!-- Another comment -->
</t>

选择了想要的评论节点并将其复制到输出中:

<!-- url path="/jsp/Admin_BetaSignup.jsp" roles="ZohoCampaignAdmin" authentication="optional" description="Page used to add the Beta users">         <param name="zuid" xss="throwerror" max-len="300"/> </url -->