2013-04-24 51 views
0

我有這種格式的XML文檔:如何轉換一個xml文檔並插入其他數據?

<?xml version="1.0" encoding="UTF-8"?> 
<person name="Bob" addr_street="123 Fake St" 
     addr_city="Springfield" addr_state="IL"/> 

我想借此數據,並通過我的代碼FigureOutZipCode(string city, string state)功能運行。

我會那麼喜歡拿這一切的組合數據,並創建一個新的文件格式爲:

<?xml version="1.0" encoding="UTF-8"?> 
<people> 
    <person> 
     <name>Bob</name> 
     <address> 
      <street>123 Fake St</address> 
      <city>Springfield</city> 
      <state>IL</state> 
      <zip>00000</zip> 
     </address> 
    </person> 
</people> 

我知道我可以只解析所有輸入XML數據的,做我的計算,然後創建一個新的輸出xml,但有沒有更好的方式去做這件事?或許像使用xslt一樣?

如果是這樣,你能提供一些關於如何做到這一點的指導嗎?

+0

對於xslt,請參閱http://stackoverflow.com/questions/10645359/convert-xml-attributes-to-elements-xslt – 2013-04-24 21:32:07

回答

1

這裏是你將如何使用XSLT做到這一點:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
       xmlns:custom="custom-functions"> 
    <xsl:output method="xml" indent="yes"/> 

    <xsl:template match="/person"> 
    <people> 
     <xsl:copy> 
     <name> 
      <xsl:value-of select="@name"/> 
     </name> 
     <address> 
      <street> 
      <xsl:value-of select="@addr_street"/> 
      </street> 
      <city> 
      <xsl:value-of select="@addr_city"/> 
      </city> 
      <state> 
      <xsl:value-of select="@addr_state"/> 
      </state> 
      <zip> 
      <xsl:value-of 
       select="custom:figureOutZipCode(@addr_city, @addr_state)"/> 
      </zip> 
     </address> 
     </xsl:copy> 
    </people> 
    </xsl:template> 
</xsl:stylesheet> 

在.NET中,調用figureOutZipCode()函數通常會涉及到傳遞一個將XSLT擴展對象添加到XSLT處理器,該文檔記錄在here中。

0

使用LINQ轉換XML到新的格式

string URL = @"location"; 
XDocument doc = XDocument.Load(URL); 

XElement newDoc = new XElement("people", 
      from p in doc.Descendants("person") 
      select new XElement("person", 
       new XElement("name", p.Attribute("name").Value), 
       new XElement("address", 
        new XElement("street", p.Attribute("addr_street").Value), 
        new XElement("city", p.Attribute("addr_city").Value), 
        new XElement("state", p.Attribute("addr_state").Value), 
        new XElement("zip", GetZip(parameters)) 
        ) 
      ) 
      ); 
+2

來自問題:「我知道我只能解析來自輸入xml的所有數據,做我的計算,然後創建一個新的輸出xml,但有沒有更好的方法去做這件事?或許像是使用xslt?' – I4V 2013-04-24 22:08:13

1

其實,還可以使用XSLT轉換的原始XML輸出新的(轉換)XML使用相同的XSLT表文件,如果使用result-document說明。這就要求撒克遜.NET XSLT解析器,請訪問:http://saxon.sourceforge.net/

信息使用result-document這裏:http://saxonica.com/documentation9.4-demo/html/xsl-elements/result-document.html

對於學習XSLT,我由邁克爾·凱(誰創造撒克遜)推薦任何東西,例如:http://www.amazon.com/XSLT-Programmers-Reference-Michael-Kay/dp/1861003129

+0

另請參見MSDN中的XslCompiledTransform類(包括示例):http://msdn.microsoft.com/en-us/library/system.xml.xsl.xslcompiledtransform(v=vs。 100)的.aspx – udog 2013-04-24 23:30:20

相關問題