XSLT with XML source that has a default namespace set to xmlns

后端 未结 3 1604
情话喂你
情话喂你 2020-11-21 23:46

I have an XML document with a default namespace indicated at the root. Something like this:


   

        
相关标签:
3条回答
  • 2020-11-22 00:17

    You need to declare the namespace in your XSLT, and use it in XPath expressions. E.g.:

    <xsl:stylesheet ... xmlns:my="http://www.mysite.com">
    
       <xsl:template match="/my:MyRoot"> ... </xsl:template>
    
    </xsl:stylesheet>
    

    Note that you must provide some prefix if you want to refer to elements from that namespace in XPath. While you can just do xmlns="..." without the prefix, and it will work for literal result elements, it won't work for XPath - in XPath, an unprefixed name is always considered to be in namespace with blank URI, regardless of any xmlns="..." in scope.

    0 讨论(0)
  • 2020-11-22 00:35

    If you use XSLT 2.0, specify xpath-default-namespace="http://www.example.com" in the stylesheet section.

    0 讨论(0)
  • 2020-11-22 00:37

    If this was kind of name space problem, there is room to try to modify two things in the xslt file:

    • add "my" name space definition in xsl:stylesheet tag
    • use "my:" prefix when call elements in traversing the xml file.

    result

    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
      xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:my="http://www.w3.org/2001/XMLSchema">
        <xsl:template match="/" >
            <soap:Envelope xsl:version="1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
                <soap:Body>
                    <NewRoot xmlns="http://wherever.com">
                        <NewChild>
                            <ChildID>ABCD</ChildID>
                            <ChildData>
                                <xsl:value-of select="/my:MyRoot/my:MyChild1/my:MyData"/>
                            </ChildData>
                        </NewChild>
                    </NewRoot>
                </soap:Body>
            </soap:Envelope>
        </xsl:template>
    </xsl:stylesheet>
    
    0 讨论(0)
提交回复
热议问题