Home >Java >javaTutorial >How to Generate XPaths for All Nodes in an XML Document Using Java?
Interested in advice rather than actual implementation. Looking for a Java approach to traverse an XML document, check nodes for attribute existence, and generate Xpaths.
To generate Xpaths for all nodes in the following XML document:
<root> <elemA>one</elemA> <elemA attribute1='first' attribute2='second'>two</elemA> <elemB>three</elemB> <elemA>four</elemA> <elemC> <elemB>five</elemB> </elemC> </root>
Expected Result:
//root[1]/elemA[1]='one' //root[1]/elemA[2]='two' //root[1]/elemA[2][@attribute1='first'] //root[1]/elemA[2][@attribute2='second'] //root[1]/elemB[1]='three' //root[1]/elemA[3]='four' //root[1]/elemC[1]/elemB[1]='five'
This solution uses an XSLT transformation to achieve the desired result:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text"/> <xsl:strip-space elements="*"/> <xsl:variable name="vApos"'>'</xsl:variable> <xsl:template match="*[@* or not(*)] "> <xsl:if test="not(*)"> <xsl:apply-templates select="ancestor-or-self::*" mode="path"/> <xsl:value-of select="concat('=',$vApos,.,$vApos)"/> <xsl:text>
</xsl:text> </xsl:if> <xsl:apply-templates select="@*|*"/> </xsl:template> <xsl:template match="*" mode="path"> <xsl:value-of select="concat('/',name())"/> <xsl:variable name="vnumPrecSiblings" select="count(preceding-sibling::*[name()=name(current())])"/> <xsl:if test="$vnumPrecSiblings"> <xsl:value-of select="concat('[', $vnumPrecSiblings +1, ']')"/> </xsl:if> </xsl:template> <xsl:template match="@*"> <xsl:apply-templates select="../ancestor-or-self::*" mode="path"/> <xsl:value-of select="concat('[@',name(), '=',$vApos,.,$vApos,']')"/> <xsl:text>
</xsl:text> </xsl:template> </xsl:stylesheet>
When applied to the provided XML document, it produces the expected Xpaths.
The above is the detailed content of How to Generate XPaths for All Nodes in an XML Document Using Java?. For more information, please follow other related articles on the PHP Chinese website!