2

I have an the incoming XML file like this.

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

I want to save an XML File as below in c#.

<sport>
<id>23></id>
<name>Basketbol</name>
<Country>
<id>15</id>
<name>A.B.D.</name>
4
  • 1
    What code have you tried so far? Commented May 5, 2011 at 17:56
  • Related: stackoverflow.com/questions/1351420 Commented May 5, 2011 at 17:57
  • 3
    Take a look at XSLT's, they are designed for this type of work. Commented May 5, 2011 at 17:58
  • Related: stackoverflow.com/questions/3885795 Commented May 5, 2011 at 18:00

1 Answer 1

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");
Sign up to request clarification or add additional context in comments.

2 Comments

If you're loading in the destination doc, then I would think you'd want to add the new xml to the root of it: destDoc.Root.Add(newElement);. Otherwise, you'd probably want create a new doc, and save it at the end.
The idea there was that I create a new document. I'll correct that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.