Selecting the children of first result using xpath

怎甘沉沦 提交于 2019-12-01 21:32:39

Use:

(/*/*//product[@id='ABC123']/sizes)[1]/size

Or use:

((/*/*/product | /*/*/products/product)/sizes)[1]/size

XSLT - based verification:

<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=
    "(/*/*//product[@id='ABC123']/sizes)[1]/size"/>
========
  <xsl:copy-of select=
    "((/*/*/product | /*/*/products/product)/sizes)[1]/size"/>

 </xsl:template>
</xsl:stylesheet>

When this transformation is applied to the provided XML document (after correcting it into a well-formed one):

<root>
    <category id="1">
        <product id="ABC123" >
            <sizes>
                <size name="S"/>
                <size name="M"/>
                <size name="L"/>
                <size name="XL"/>
                <size name="2XL"/>
                <size name="3XL"/>
            </sizes>
        </product>
    </category>
    <category id="2">
        <products>
            <product id="ABC123" >
                <sizes>
                    <size name="S"/>
                    <size name="M"/>
                    <size name="L"/>
                    <size name="XL"/>
                    <size name="2XL"/>
                    <size name="3XL"/>
                </sizes>
            </product>
            <product id="PPP543" >
                <sizes>
                    <size name="S"/>
                    <size name="M"/>
                    <size name="L"/>
                    <size name="XL"/>
                </sizes>
            </product>
        </products>
    </category>
</root>

the two XPath expressions are evaluated and the selected nodes from each one, well visually delimited, are copied to the output -- both correct:

<size name="S"/>
<size name="M"/>
<size name="L"/>
<size name="XL"/>
<size name="2XL"/>
<size name="3XL"/>
========
  <size name="S"/>
<size name="M"/>
<size name="L"/>
<size name="XL"/>
<size name="2XL"/>
<size name="3XL"/>

Do note: I expect the second XPath expression to be more efficient (on sufficiently large documents), because it doesn't use the // pseudo-operator.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!