Selecting/matching elements in a namespace

后端 未结 2 1833
渐次进展
渐次进展 2020-12-22 05:49

I have a xml and xsl that need to generate another xml, but because of \'xmlns\', it generates an empty xml. Without \'xmlns\' in the root of XML, it works fine. The follow

相关标签:
2条回答
  • 2020-12-22 06:22

    Use xsl:element with namespace attribute

    <xsl:template  match="config">
      <xsl:element namespace="http://xmlns.company.com/config" name="config">
         <sub-config>
           <primary-data-source><xsl:value-of select="sub-config/primary-data-source"/></primary-data-source>
           <xsl:apply-templates select="sub-config"/>
        </sub-config>
      </xsl:element>
    
    </xsl:template>
    

    It will create element with computed name( Static for us ) and allow to add namespace attribute

    0 讨论(0)
  • 2020-12-22 06:32

    You need to assign a prefix to the namespace and use that prefix when addressing the elements of the source XML:

    <?xml version="1.0" encoding="UTF-8"?>
    <xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:cfg="http://xmlns.company.com/config"
    exclude-result-prefixes="cfg"> 
    
    <xsl:output method="xml" encoding="UTF-8"  indent="yes"/>
    
    <xsl:template match="/">
        <xsl:apply-templates  select="cfg:config"/>
    </xsl:template>
    
    <xsl:template  match="cfg:config">
        <config>
            <sub-config>
                <primary-data-source>
                    <xsl:value-of select="cfg:sub-config/cfg:primary-data-source"/>
                </primary-data-source>
                <xsl:apply-templates select="cfg:sub-config"/>
            </sub-config>
        </config>
    </xsl:template>
    
    <xsl:template match="cfg:sub-config">
        <xsl:for-each select="cfg:instance">
            <instance>
                <name><xsl:value-of select="cfg:name"/></name>
                <address><xsl:value-of select="cfg:address"/></address>
                <port><xsl:value-of select="cfg:port"/></port>
                <admin-username><xsl:value-of select="cfg:admin-username"/></admin-username>
            </instance>
        </xsl:for-each>
    </xsl:template>
    
    </xsl:stylesheet>
    

    Note that sub-config and subi-config are two different things.

    0 讨论(0)
提交回复
热议问题