sorting xml file using linq
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>
开发者_StackOverflow中文版<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
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.
精彩评论