2013-04-08 71 views
-2

我有一个关于转换xml文件的问题。 我的XML文件(XML1),其具有这样的结构:将xml文件转换为其他xml格式

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

我已了解我可以转化一个XML到其它使用XSLT我。如何可以生成XSL样式表?存在C#中的设计师?

谁能告诉我怎样才能改变这种XML文件格式,以这种格式(XML2)使用XSL样式表在C#:

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

StackOverflow不是代码写入服务。请阅读[提问一个好问题的指南](http://tinyurl.com/so-hints)并显示[你尝试过的](http://whatyouhavetried.com)。 – 2013-04-08 12:48:04

+0

你会得到什么错误? – 2013-04-08 12:59:45

+0

http://en.wikipedia.org/wiki/XSL_Transformations可能会有帮助。不幸的是,它看起来可能没有任何C#本质。 – 2013-04-08 13:04:26

回答

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>