2

how to sort nodes in the xml file and save file in sorted order using linq?

if this is my xml file,

<Persons>
  <Person>
    <id>2</id>
    <Name>xxx</Name>
  </Person>
  <Person>
    <id>3</id>
    <Name>yyy</Name>
    </Person>
</Persons>

when inserting new node., it should be inserted as like this.

<Persons>
          <Person>
            <id>1</id>
            <Name>zzz</Name>
          </Person>
          <Person>
            <id>2</id>
            <Name>xxx</Name>
          </Person>
          <Person>
            <id>3</id>
            <Name>yyy</Name>
            </Person>
    </Persons>

how to do this using linq?

thank you

1
  • Could you use the answer or is there something unclear? regards Commented Jul 28, 2010 at 0:15

1 Answer 1

4

Something like the following. You should properly use int.TryParse instead of int.Parse and some other checks (for specific elements etc.) if your are not 100% sure of the input. Or check it against a schema.

(I have added a person in the end with id=1. I guess your forgot to add it.)

var doc = XDocument.Parse(@"<Persons>
<Person>
<id>2</id>
<Name>xxx</Name>
</Person>
<Person>
<id>3</id>
<Name>yyy</Name>
</Person>
<Person>
<id>1</id>
<Name>some name</Name>
</Person>
</Persons>");

//By building a new XDocument
var newDoc = new XDocument(new XElement("Persons",
                from p in doc.Element("Persons").Elements("Person")
                orderby int.Parse(p.Element("id").Value)
                select p));
//or by changing the original XDocument (does not change it where you got it from - a file etc.):

doc.Root.ReplaceAll(from p in doc.Root.Elements("Person")
                    orderby int.Parse(p.Element("id").Value)
                    select p);

And to load/save your can use:

var doc = XDocument.Load("filename"); //Or use a stream etc.
newDoc.Save("filename"); //Or save to a stream etc.

You can use:

doc.Root

instead of:

doc.Element("Persons")

But again, check the elements if your not 100% sure of the input.

Sign up to request clarification or add additional context in comments.

Comments

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.