将xml文件转换为其他xml格式

时间:2013-04-08 12:47:22

标签: c# xml xslt

我有一个关于转换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>

1 个答案:

答案 0 :(得分:0)

通过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>
相关问题