使用XSLT从SOAP消息中选择节点值

时间:2015-02-11 13:43:45

标签: xml xslt soap

我正在尝试从SOAP消息中获取值。我需要检索用户名和密码。

SOAP消息如下所示:

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://www.w3.org/2003/05/soap-envelope">
  <soap:Header></soap:Header>
  <soap:Body>    
     <GetData xmlns="http://webservicedata.com/">   
      <oXmlElement>
        <message>
          <header>
            <username>test@gmail.com</username>
            <password>Test password</password>
          </header>
        </message>
      </oXmlElement>
    </GetData>    
  </soap:Body>
</soap:Envelope>

这是我的XSLT

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:soap="http://www.w3.org/2003/05/soap-envelope" exclude-result-prefixes="soap msxsl">
  <xsl:output method="xml" indent="yes"/>
  <xsl:template match="/">
    <NewDataSet>
      <Header>           
        <username>
          <xsl:value-of select="soap:Envelope/soap:Body/GetData/oXmlElement/message/header/username"/>
        </username>
        <password>
          <xsl:value-of select="soap:Envelope/soap:Body/GetDate/oXmlElement/message/header/password"/>
        </password>
      </Header>
    </NewDataSet>
  </xsl:template>
</xsl:stylesheet>

如果删除<GetData xmlns="http://webservicedata.com/">

,以下是可行的结果
<?xml version="1.0" encoding="UTF-8"?>
<NewDataSet>
   <Header>
      <Portfolio />
      <username>test@gmail.com</username>
      <password>testpassword</password>
   </Header>
</NewDataSet>

1 个答案:

答案 0 :(得分:1)

xmlns="http://webservicedata.com/" GetData将其及其所有未加前缀的后代元素放入命名空间,因此您必须将该命名空间映射到样式表中的前缀并在XPath表达式中使用前缀 - 未加前缀的名称在XPath 1.0 总是引用 no 命名空间中的元素。

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:msxsl="urn:schemas-microsoft-com:xslt"
    xmlns:soap="http://www.w3.org/2003/05/soap-envelope"
    xmlns:wsd="http://webservicedata.com/"
    exclude-result-prefixes="soap msxsl wsd">
  <xsl:output method="xml" indent="yes"/>
  <xsl:template match="/">
    <NewDataSet>
      <Header>           
        <username>
          <xsl:value-of select="soap:Envelope/soap:Body/wsd:GetData/wsd:oXmlElement/wsd:message/wsd:header/wsd:username"/>
        </username>
        <!-- similar for password -->
      </Header>
    </NewDataSet>
  </xsl:template>
</xsl:stylesheet>