使用C#读取XML属性

时间:2011-05-05 17:54:45

标签: c# xml

我有一个这样的传入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 个答案:

答案 0 :(得分: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");