如何使用 linq 对 xml 文件中的节点进行排序并按排序顺序保存文件?
如果这是我的 xml 文件,
<Persons>
<Person>
<id>2</id>
<Name>xxx</Name>
</Person>
<Person>
<id>3</id>
<Name>yyy</Name>
</Person>
</Persons>
插入新节点时, 它应该像这样插入。
<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>
如何使用 linq 执行此操作?
谢谢
最佳答案
类似下面的内容。如果您不能 100% 确定输入,您应该正确使用 int.TryParse 而不是 int.Parse 和其他一些检查(针对特定元素等)。或者根据架构检查它。
(我最后添加了一个 id=1 的人。我猜你忘记添加了。)
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);
要加载/保存您可以使用:
var doc = XDocument.Load("filename"); //Or use a stream etc.
newDoc.Save("filename"); //Or save to a stream etc.
您可以使用:
doc.Root
而不是:
doc.Element("Persons")
但是,如果您不能 100% 确定输入,请再次检查元素。
关于c# - 使用linq对xml文件进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3334775/