使用XSLT将新节点添加到现有XML的特定位置



我的原始XML:

<customers>
    <client>
        <custnum>1</custnum>
        <name>John</name>
    </client>
    <client>
        <custnum>2</custnum>
        <name>Mary</name>
    </client>
</customers>

附加XML (updates.xml)

<root>
    <something>
        <custnum>1</custnum>
        <ssn>67890</ssn>
    </something>
    <something>
        <custnum>2</custnum>
        <ssn>12345</ssn>
    </something>
    <something>
        <custnum>3</custnum>
        <ssn>11111</ssn>
        <name>Mart</name>
    </something>
</root>
所需输出

    <customers>
      <client>
        <custnum>1</custnum>
        <name>John</name>
        <ssn>67890</ssn>
      </client>
      <client>
        <custnum>2</custnum>
        <name>Mary</name>
        <ssn>12345</ssn>
      </client>
    </customers>

目前我正在使用以下XSL,我从Stackoverflow中找到:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:strip-space elements="*"/>
  <xsl:output method="xml" indent="yes" />
  <xsl:key name="cust" match="something" use="custnum" />

  <xsl:template match="@*|node()">
    <xsl:copy><xsl:apply-templates select="@*|node()" /></xsl:copy>
  </xsl:template>

  <xsl:template match="client">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()" />
      <xsl:variable name="myId" select="custnum" />
        <xsl:for-each select="document('updates.xml')">
          <!-- process all transactions with the right ID -->
          <xsl:apply-templates select="key('cust', $myId)" />
        </xsl:for-each>
    </xsl:copy>
  </xsl:template>
  <xsl:template match="something/custnum" />
</xsl:stylesheet>

生成

<customers>
  <client>
    <custnum>1</custnum>
    <name>John</name>
    <something>
      <ssn>67890</ssn>
    </something>
  </client>
  <client>
    <custnum>2</custnum>
    <name>Mary</name>
    <something>
      <ssn>12345</ssn>
    </something>
  </client>
</customers>

我如何摆脱<something>标签,而不处理结果与另一个XSL?它应该是相当简单的,但它就是不适合我。

如果您只想获取ssn,那么为什么不获取ssn呢?

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:key name="cust" match="something" use="custnum" />
<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>
<xsl:template match="client">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()" />
        <xsl:variable name="myId" select="custnum" />
        <xsl:for-each select="document('updates.xml')">
            <xsl:apply-templates select="key('cust', $myId)/ssn" />
        </xsl:for-each>
    </xsl:copy>
</xsl:template>
</xsl:stylesheet>

相关内容

  • 没有找到相关文章

最新更新