2013-04-08 70 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>