XSLT转换需要添加SOAP信封并在SOAP标头和正文之间拆分XML

时间:2017-12-21 18:42:57

标签: xslt soap

我尝试了各种博客中提出的几个选项,但想知道以下转换是否可行。

我需要转换以下XML,

<?xml version="1.0" encoding="UTF-8"?>
<ns1:ReturnLicensesForHost xmlns:ns1="http://example.com">
  <ns1:userName>ABCDEFGH</ns1:userName>
  <ns1:password>1234567</ns1:password>
  <ns1:hostIdType>XYZ</ns1:hostIdType>
  <ns1:hostId>987654</ns1:hostId>
  <ns1:product>STUV</ns1:product>
</ns1:ReturnLicensesForHost>

<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:fs="http://example.com">
   <soap:Header>
      <fs:Credentials>
         <fs:userName>ABCDEFGH</fs:userName>
         <fs:password>1234567</fs:password>
      </fs:Credentials>
   </soap:Header>
   <soap:Body>
      <fs:ReturnLicensesForHost>
         <fs:hostIdType>XYZ</fs:hostIdType>
         <fs:hostId>987654</fs:hostId>
         <fs:product>STUV</fs:product>
      </fs:ReturnLicensesForHost>
   </soap:Body>
</soap:Envelope>

基本上,我需要添加一个SOAP信封,并在Header和Body之间拆分字段 请求您使用XSLT进行此转换。

1 个答案:

答案 0 :(得分:1)

转换只需将结果XML放在模板中,并用引用输入XML的xsl:value-of短语替换所需的值(包括命名空间管理):

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:ns1="http://example.com"> 
<xsl:output method="xml" indent="yes" />    

  <xsl:template match="/ns1:ReturnLicensesForHost">
    <soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:fs="http://example.com">
        <soap:Header>
            <fs:Credentials>
                <fs:userName><xsl:value-of select="ns1:userName" /></fs:userName>
                <fs:password><xsl:value-of select="ns1:password" /></fs:password>
            </fs:Credentials>
        </soap:Header>
        <soap:Body>
            <fs:ReturnLicensesForHost>
                <fs:hostIdType><xsl:value-of select="ns1:hostIdType" /></fs:hostIdType>
                <fs:hostId><xsl:value-of select="ns1:hostId" /></fs:hostId>
                <fs:product><xsl:value-of select="ns1:product" /></fs:product>
            </fs:ReturnLicensesForHost>
        </soap:Body>
    </soap:Envelope>   
  </xsl:template>

</xsl:stylesheet>

<强>输出:

<?xml version="1.0"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:fs="http://example.com" xmlns:ns1="http://example.com">
    <soap:Header>
        <fs:Credentials>
            <fs:userName>ABCDEFGH</fs:userName>
            <fs:password>1234567</fs:password>
        </fs:Credentials>
    </soap:Header>
    <soap:Body>
        <fs:ReturnLicensesForHost>
            <fs:hostIdType>XYZ</fs:hostIdType>
            <fs:hostId>987654</fs:hostId>
            <fs:product>STUV</fs:product>
        </fs:ReturnLicensesForHost>
    </soap:Body>
</soap:Envelope>