2011-05-05 104 views
2

我有一個像這樣的傳入XML文件。用C讀取XML屬性#

<Sport id="23" name="Basketbol"> 
<Country id="15" name="A.B.D."> 
    <Tournament id="9" name="Amerikan Basketbol Ligi" type="1" typeDesc="League"> 
    <Season id="95" name="2010/2011"> 
     <Stage id="777" name="2010/2011 Sezonu"> 
     <Team id="104" name="Chicago Bulls" conferenceId="3" conference="Merkez"> 
      <General position="1" totalPlayed="82" won="62" draw="0" lost="20" goalsScored="8087" goalsAgainst="7485" points="144" form="W- W- W- W- W- W" /> 
      <Home position="1" totalPlayed="41" won="36" draw="0" lost="5" goalsScored="4104" goalsAgainst="3683" points="77" /> 
      <Away position="4" totalPlayed="41" won="26" draw="0" lost="15" goalsScored="3983" goalsAgainst="3802" points="67" /> 
     </Team> 

我想在c#中保存如下的XML文件。

<sport> 
<id>23></id> 
<name>Basketbol</name> 
<Country> 
<id>15</id> 
<name>A.B.D.</name> 
+1

你試過到目前爲止什麼碼? – 2011-05-05 17:56:26

+0

相關:http://stackoverflow.com/questions/1351420 – 2011-05-05 17:57:05

+3

看看XSLT的,他們是專爲這種類型的工作。 – Jon 2011-05-05 17:58:10

回答

3

LinqToXml:http://msdn.microsoft.com/en-us/library/bb387098.aspx

using System.Xml.Linq; 
// [...]  

var sourceDoc = XDocument.Load(@"C:\Your\Source\Xml\File.xml"); 
var sports = sourceDoc.Descendants().Where(s => s.Name == "Sport"); 

var destDoc = new XDocument(sports.Select(s => 
    new XElement("sport", 
     new XElement("id", s.Attribute("id").Value), 
     new XElement("name", s.Attribute("name").Value), 
     new XElement("country", 
      new XAttribute("id", s.Descendants().Where(c => c.Name == "Country").FirstOrDefault().Attribute("id").Value), 
      new XAttribute("name", s.Descendants().Where(c => c.Name == "Country").FirstOrDefault().Attribute("name").Value) 
     ) 
    ) 
)); 

destDoc.Save(@"C:\Your\Destination\Xml\File.xml"); 
+0

如果你正在加載目標文檔,那麼我會認爲你想添加新的xml到它的根目錄:'destDoc.Root.Add (爲newElement);'。否則,你可能想創建一個新的文檔,並保存在最後。 – 2011-05-05 18:04:31

+0

這個想法是我創建了一個新文檔。我會糾正這一點。 – LueTm 2011-05-06 11:39:44

+0

@ LueTm-非常感謝你。 – Arbelac 2011-05-07 14:20:15