首页 > 解决方案 > 我想在不更改其属性的情况下将 xml 元素“产品”重命名为“项目”,但我不知道该怎么做

问题描述

输入 XML:

<ProductList>
    <Product Action="Manage" ProductID="Item_1">
        <PrimaryInformation Description="Item 1"
            Status="3000" ShortDescription="Item 1" />
    </Product>
    <Product Action="Manage" ProductID="Item_2">
        <PrimaryInformation Description="Item 2"
            Status="3000" ShortDescription="Item 2" />
    </Product>
    <Product Action="Manage" ProductID="Item_3">
        <PrimaryInformation Description="Item 3"
            Status="3000" ShortDescription="Item 3" />
    </Product>
</ProductList>

预期的 XML 输出:

<ProductList >
  <Item Action="Manage" ProductID="Item_1" >
   <PrimaryInformation Description="Item 1" Status="3000" ShortDescription="Item 1" /> 
 </Item> 
 <Item Action="Manage" ProductID="Item_2" >
   <PrimaryInformation Description="Item 2" Status="3000" ShortDescription="Item 2" /> 
 </Item>
  <Item Action="Manage" ProductID="Item_3" > 
  <PrimaryInformation Description="Item 3" Status="3000" ShortDescription="Item 3" />
  </Item>
 </ProductList>

我尝试了这个 XML 模板,它正在工作,但它也删除了该元素中存在的所有属性。

<xsl:template match="Product">
    <xsl:element name="Item">
        <xsl:apply-templates />
    </xsl:element>
</xsl:template>

标签: xmlxsltxml-parsing

解决方案


请尝试以下 XSLT。

它遵循身份转换模式。

XSLT

<?xml version='1.0'?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
   <xsl:output method="xml" encoding="utf-8" indent="yes" omit-xml-declaration="yes"/>
   <xsl:strip-space elements="*"/>

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

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

推荐阅读