B
B
beduin012019-04-19 09:49:34
XPath
beduin01, 2019-04-19 09:49:34

How to check if a section of a tree exists in XML?

Interested in any way to check if a branch exists in the XML tree. In xpath, I found the ability to check only the existence of individual tags. But you need the ability to check the existence of a tree of the form foo/bar/baz

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Fov, 2019-04-19
@Roman-Fov

So count them same
XML

<root>
  <foo>
    <bar>
      <baz>asdf</baz>
      <text>text1</text>
    </bar>
  </foo>
  <foo>
    <bar>
      <text>text2</text>
    </bar>
  </foo>
  <foo>
    <bar>
      <baz>3</baz>
      <text>text3</text>
    </bar>
  </foo>
</root>

XSLt
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="/root">
    <xsl:apply-templates select="foo"/>
  </xsl:template>

  <xsl:template match="foo">
    <h1 style="color:red;">
      <xsl:attribute name="style">
        <xsl:choose>
          <xsl:when test="count(bar/baz) &gt; 0">
            <xsl:text>color: red;</xsl:text>
          </xsl:when>
          <xsl:otherwise>
            <xsl:text>color: green;</xsl:text>
          </xsl:otherwise>
        </xsl:choose>
      </xsl:attribute>
      <xsl:apply-templates select="bar/text"/>
    </h1>
  </xsl:template>
</xsl:stylesheet>

result
<h1 style="color: red;">text1</h1>
<h1 style="color: green;">text2</h1>
<h1 style="color: red;">text3</h1>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question