首页 文章

如何使用XSLT将文本插入xml节点

提问于
浏览
0

我有一个xml我想修改如下

我想将文本插入指定节点

XML

<wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
         <wsse:UsernameToken xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
                             wsu:Id="UsernameToken-80842">
            <wsse:Username>test</wsse:Username>
            <wsse:Password>password</wsse:Password>
         </wsse:UsernameToken>
      </wsse:Security>
   </soap:Header>

我可以使用什么XSLT将值插入wsse:Password节点,例如 . 所以它是

<wsse:Password Type="blabla">password</wsse:Password>

我怎么能用xslt做到这一点?

1 回答

  • 0

    您的示例中的XSLT 1.0(照顾您的命名空间):

    <?xml version="1.0" encoding="UTF-8"?>
    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
        xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
        xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
        version="1.0">
    
        <xsl:template match="@* | node()">
            <xsl:copy>
                <xsl:apply-templates select="@* | node()"/>
            </xsl:copy>
        </xsl:template>
    
        <xsl:template match="wsse:Password">
            <xsl:copy>
                <xsl:text>abc</xsl:text>
            </xsl:copy>
        </xsl:template>
    
    </xsl:stylesheet>
    

    Result

    <?xml version="1.0" encoding="UTF-8"?><wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
        <wsse:UsernameToken xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="UsernameToken-80842">
            <wsse:Username>test</wsse:Username>
            <wsse:Password>abc</wsse:Password>
        </wsse:UsernameToken>
    </wsse:Security>
    

    EDIT 1:

    <wsse:密码类型=“blabla”>密码</ wsse:密码>

    有一些不同的方法来创建属性:

    I.

    <xsl:template match="wsse:Password">
        <xsl:copy>
            <xsl:attribute name="Type">
                <!--
                    <xsl:text></xsl:text>
                    <xsl:value-of select="..."/>
                    <xsl:apply-templates select="..."/>
                -->
            </xsl:attribute>
            <xsl:value-of select="."/>
        </xsl:copy>
    </xsl:template>
    

    II.

    <xsl:template match="wsse:Password">
        <wsse:Password Type="{concat('ab', 'cd')}">
            <xsl:apply-templates/>
        </wsse:Password>
    </xsl:template>
    

    第二部分:如果你想为属性"type"使用xpath,你必须使用{},否则你有一个consant字符串值,你可以像 Type="world" 一样编写它 .

相关问题