首页 > 解决方案 > 删除 XML 中的子节点并使用 XSLT 将其数据复制到父节点

问题描述

我正在尝试消除所有子节点并将所有数据复制到父节点,但输出与输入保持相同。

输入 XML -

<?xml version="1.0" encoding="ISO-8859-1"?>
<PersonData>    
    <Header>
    </Header>
    <Person>
      <Personal>
         <FirstName>abc</FirstName>
         <LastName>cde</LastName>
         <ID>12345</ID>
      </Personal>
      <AddressData>
         <Address1>abc123</Address1>
         <Address2>def345</Address2>
      </AddressData>
      <PhoneData>
         <Phone1>111111111</Phone1>
      </PhoneData>
    </Person>
 </PersonData>

我已经尝试过下面的代码,但输出与输入保持相同,因此不会删除子节点,并且保留在其中的数据也不会移动到父节点,即人。

   <?xml version='1.0'?>
   <xsl:stylesheet version="2.0" 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

   <xsl:output method="xml" indent="yes"/>
   <xsl:strip-space elements="*" />

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

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

   </xsl:stylesheet>    

所需的输出 -

   <?xml version="1.0" encoding="ISO-8859-1"?>
   <PersonData>    
   <Person>
     <FirstName>abc</FirstName>
     <LastName>cde</LastName>
     <ID>12345</ID>
     <Address1>abc123</Address1>
     <Address2>def345</Address2>
     <Phone1>111111111</Phone1>
    </Person>
    </PersonData>

我得到与输入 XML 相同的输出,而不是没有子节点的上述预期输出

标签: xmlxsltxslt-1.0

解决方案


怎么样:

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="/PersonData">
    <xsl:copy>
        <xsl:apply-templates select="Person"/>
     </xsl:copy>
</xsl:template>

<xsl:template match="Person">
    <xsl:copy>
        <xsl:copy-of select="*/*"/>
     </xsl:copy>
</xsl:template>

</xsl:stylesheet>

推荐阅读