【问题标题】:Transform xml file into an other xml format将 xml 文件转换为其他 xml 格式
【发布时间】:2013-04-08 12:47:22
【问题描述】:

我有一个关于转换 xml 文件的问题。 我有一个 xml 文件 (xml1),它有这样的结构:

<Info>
  <cars>
   <car>
       <id>1</id>
       <brand>Pegeout</brand>
    </car>
    <car>
       <id>2</id>
       <brand>Volkwagen</brand>
    </car>
  </cars>
  <distances>
    <distance>
      <id_car>1</id_car>
      <distance_km>111</distance_km>
    </distance>
    <distance>
        <id_car>1</id_car>
        <distance_km>23</distance_km>
    </distance>
  </distances>
</Info>

我不明白我可以使用 xslt 将一个 xml 转换为另一个。如何生成 xsl 样式表?有 C# 中的设计师吗?

谁能告诉我如何使用 C# 中的 XSL 样式表将此 xml 文件格式转换为这种格式 (xml2):

<Info>
  <cars>
   <car>
       <id>1</id>
       <brand>Pegeout</brand>
       <distance>
          <distance_km>111</distance_km>
          <distance_km>23</distance_km>
       </distance>
   </car>
    <car>
       <id>2</id>
       <brand>Volkwagen</brand>
    </car>
  </cars>
</Info>

【问题讨论】:

标签: c# xml xslt


【解决方案1】:

定义一个键来通过 id 引用元素:

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

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

<xsl:key name="id" match="distance" use="id_car"/>

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

<xsl:template match="car">
  <xsl:copy>
    <xsl:apply-templates select="@* | node()"/>
    <xsl:variable name="ref-dist" select="key('id', id)/distance_km"/>
    <xsl:if test="$ref-dist">
      <distance>
        <xsl:apply-templates select="$ref-dist"/>
      </distance>
    </xsl:if>
  </xsl:copy>
</xsl:template>

<xsl:template match="Info/distances"/>

</xsl:stylesheet>

【讨论】:

    猜你喜欢
    • 2021-01-18
    • 1970-01-01
    • 2012-12-20
    • 2014-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-13
    相关资源
    最近更新 更多