0

我收到不同命名空间的输入请求,如“pn”、“tmn”、“pn2”、“pn3”。我必须只获取具有命名空间“pn2”、“pn3”的元素并排除其余元素与其他命名空间。我应该如何在 XSLT 中编写这个?

这是我的示例传入请求:

 <soap-env:Envelope
xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/"
>
<soap-env:Header/>
<soap-env:Body>
<Details actionCode="04">
<Info>123</Info>
<ID>ABC12</ID>
                        <pn2:Address
                        xmlns:pn2="http://www.blah2.com/"
                        >Address</pn2:Address>
                        <pn3:City cityID=" " scID=" " ID=" "
                        xmlns:pn3="http://www.blah3.com/"
                        >City</pn3:City>
                        <tmn:City cityID=" " scID=" " ID=" "
                        xmlns:tmn="http://www.blah.com/"
                        >City1</tmn:City>
                        <Address>       
                            <pn2:PermAddress xmlns:pn2="http://www.blah2.com/"
                             >Address1</pn2:PermAddress>
                            <tmn:Street StreetID=" " scID=" " ID=" "
                             xmlns:tmn="http://www.blah.com/"
                            >Street1</tmn:Street>
                            <pn:Estate StateID=" " SID=" " ID=" " xmlns:pn="http://www.blah1.com/"
                             >Estate</pn:Estate>
                            <pn3:Place xmlns:pn3="http://www.blah3.com/">Place</pn3:Place>
                        </Address>  
                       </Details>
                     </soap-env:Body>

</soap-env:Envelope>
                

XSLT 我试过:

<xsl:template match="Details//*">
    <xsl:element name="{local-name()}">
      <xsl:apply-templates select="node()|@*"/>
    </xsl:element>
  </xsl:template>
   <xsl:template match="Details//@*">
    <xsl:copy-of select="."/>
  </xsl:template>

我可以删除命名空间,但不能删除 XSLT 中的元素。

4

1 回答 1

3

这是您可以查看的一种方式:

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="*">
    <!-- exclude text nodes -->
    <xsl:apply-templates select="*"/>
</xsl:template>

<xsl:template match="*[not(namespace-uri()) or starts-with(name(), 'pn2:') or starts-with(name(), 'pn3:')]">
    <xsl:element name="{local-name()}">
        <xsl:copy-of select="@*"/>
        <xsl:apply-templates/>
    </xsl:element>
</xsl:template>

</xsl:stylesheet>

一种更聪明的方法可能是忽略前缀并将选择基于实际的命名空间 URI - 即:

<xsl:template match="*[not(namespace-uri()) or namespace-uri()='http://www.blah2.com/' or namespace-uri()='http://www.blah3.com/']">
于 2021-01-07T13:19:45.280 回答