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

时间:2015-10-21 08:02:56

标签: xml xslt xslt-1.0

我原来的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>

目前我使用的是从Stackoverflow找到的以下XSL:

<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>

如何在不使用其他XSL处理结果的情况下删除<something>标记?它应该相当简单,但它不会为我点击。

1 个答案:

答案 0 :(得分:0)

如果您只想获取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>