Problem with XSLT and namespaces

I am new to XSLT, so other times could answer this question. I searched but found nothing :(

I need to parse XML like this

<ns1:tagName1>
    <ns2:tagName2>
          This is the content
    </ns2:tagName2>       
</ns1:tagName1>

And I use this XSL for this

<xsl:template match="ns1:tagName1">
    <resultns1>
        <xsl:if test="ns2:tagName2">
            <resultns2>
                <xsl:value-of select=".">
            </resultns2>
        </xsl:if>
    </resultns1>
</xsl:template>

The result that I expect

<resultns1>
    <resultns2>
        This is the content
    </resultns2>       
</resultns1>

but instead, all I get is

<resultns1/>

If both tags use the same namespace, everything works as expected, but if the outer tag is in ns1 and the inner one is in ns2, then the inner one is not found. Any clues on why this is happening?

Thanks!

+3
source share
3 answers

This works great for me; XML:

<?xml version="1.0" encoding="utf-8" ?>
<xml xmlns:ns1="foo" xmlns:ns2="bar">
  <ns1:tagName1>
    <ns2:tagName2>
      This is the content
    </ns2:tagName2>
  </ns1:tagName1>
</xml>

XSLT:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:ns1="foo" xmlns:ns2="bar"
    exclude-result-prefixes="ns1 ns2"
>
  <xsl:template match="/xml">
    <xsl:apply-templates select="*"/>
  </xsl:template>

  <xsl:template match="ns1:tagName1">
    <resultns1>
      <xsl:if test="ns2:tagName2">
        <resultns2>
          <xsl:value-of select="."/>
        </resultns2>
      </xsl:if>
    </resultns1>
  </xsl:template>
</xsl:stylesheet>

Result:

<?xml version="1.0" encoding="utf-8"?>
<resultns1>
  <resultns2>
    This is the content
  </resultns2>
</resultns1>
+4
source

XSLT , XML. , ns2 ? , ( ) - . .

, , XML XSLT , , ?

+1

Ouch!

XML XSLT , , , :(

, , ,

, :)

0

Source: https://habr.com/ru/post/1705461/


All Articles