gpt4 book ai didi

c# - 使用linq对xml文件进行排序

转载 作者:行者123 更新时间:2023-11-30 21:20:21 24 4
gpt4 key购买 nike

如何使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com