0

Input XML file:

<a>
  <Item key="1">
    <c1>
      <d11>
      </d11>
      <d12 value="1" />
      <d13 />
    </c1>
  </Item>

  <b2>
    <Item key="fix">
      <d21>
      </d21>
      <d22 value="yes" />
      <d23 />
    </Item>
  </b2>

  <b3>
    <c3>
      <d31>
      </d31>
      <Item key="price">
        <e2 value="no" />
        <e3 />
      </Item>
    </c3>
  </b3>
</a>

How can I write a .xsl stylesheet so that the outputs are like this:

a/Item [@key='1']/c1/d12/@value
a/b2/Item [@key='fix']/d22/@value
a/b3/с2/Item[@key='price']/e2/@value

That is, the full path to a tag with an @value attribute can contain an Item tag with a special value for the key attribute.

6
  • Your input has no value attributes. See here how to generate a path to a node: stackoverflow.com/a/65293329/3016153 Commented Nov 10, 2021 at 11:41
  • Sorry, fixed the value attributes in the input xml file Commented Nov 11, 2021 at 4:35
  • 2
    Good. Now you have an example, so if you get stuck post your attempt so we can fix it, instead of having to write your code for you from scratch. Commented Nov 11, 2021 at 5:52
  • don't understand how to stop at a node with @value attribute Commented Nov 12, 2021 at 2:46
  • xsltfiddle.liberty-development.net/jxWVfBU/3 Commented Nov 12, 2021 at 4:30

1 Answer 1

1

How about something simple:

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" encoding="UTF-8"/>

<xsl:template match="/">
    <xsl:for-each select="//@value">
        <xsl:for-each select="ancestor::*">
            <xsl:value-of select="name()"/>
            <xsl:if test="@key">
                <xsl:text>[@key="</xsl:text>
                <xsl:value-of select="@key"/>
                <xsl:text>"]</xsl:text>
            </xsl:if>
            <xsl:text>/</xsl:text>
        </xsl:for-each>
        <xsl:text>@value&#10;</xsl:text>
    </xsl:for-each>
</xsl:template> 

</xsl:stylesheet>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.