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

标签 c# linq-to-xml

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

相关文章:

c# - 在 C# 中概括和聚合 XML 转储的最佳方法是什么?

c# - Linq 2 XML 不返回基于属性值的元素

c# - 围绕 SqlTransaction 回滚的异常处理

c# - stdout 和 stderr 的 Process.Start 缓冲区大小是多少?

c# - Web Api HTTPPost 不接受 int

linq - 使用 Linq to Xml 获取值(value)

c# - 这两种任务方法的行为有何不同?

javascript - 在正则表达式中,我需要仅在中间允许空格并在开头和结尾处防止空格

c# - 使用 LINQ to XML 处理简单的 XML 文件 : overkill? 或者没有更糟?

c# - 使用 LINQ 将数据表转为 XML