c# LINQ-to-XML 在排序后更新(保存)文件中的元素列表

标签 c# xml linq linq-to-xml xelement

我有一个这样的 XML 文件:

<?xml version="1.0" encoding="utf-8"?>
<FooMgr>
    <BlargDate>2017-03-06 10:26:21</BlargDate>
    <Bars>
        <Bar>
            <BarId>222</BarId>
            <BarVal>QWERTY</BarVal>
        </Bar>
        <Bar>
            <BarId>77</BarId>
            <BarVal>DVORAK</BarVal>
        </Bar>
        <Bar>
            <BarId>9999</BarId>
            <BarVal>AZERTY</BarVal>
        </Bar>
    </Bars>
</FooMgr>

我是:

  • 阅读它
  • 添加“条形”元素
  • 按 BarId 降序排列
  • 尝试将更新/排序的 xml保存回文件。

虽然我保存后添加的元素在列表中,但是保存时并没有保持我在代码中定义的顺序。这是我到目前为止所做的(主要是工作有效代码)

//read in the xml file
XDocument doc = XDocument.Load(...);

//add a new 'Bar' element
XElement bar1 = new XElement("Bar",
                      new XElement("BarId", 101),
                      new XElement("BarVal", "HCESAR"));
doc.Element("FooMgr").Element("Bars").Add(bar1);

//sort descending by BarId
IEnumerable<XElement> allBars = doc.Descendants("FooMgr")
                                   .Select(x => x.Element("Bars"))
                                   .Descendants("Bar")
                                   .ToArray();
allBars = allBars.OrderByDescending(s => int.Parse(s.Element("BarId").Value));

//save file
doc.Save(...);

// note: at this point the file successfully saves (along with the 
// new 'bar' value, but the order that is set for allBars does not 
// make it back into the file.

虽然这一行:

allBars = allBars.OrderByDescending(s => int.Parse(s.Element("BarId").Value));

似乎确实正确地对代码中的“条形图”元素进行了排序,当我将其保存回文件时,顺序不会保留。

有什么想法吗?

最佳答案

您可以在调用 Save 方法之前执行此操作:

//Remove bar elements from your doc
doc.Element("FooMgr").Element("Bars").Elements("Bar").Remove();
//Add the ordered bar nodes
doc.Element("FooMgr").Element("Bars").Add(allBars);

//save file
doc.Save(...);

关于 Remove 的更多信息扩展方法和Add方法

关于c# LINQ-to-XML 在排序后更新(保存)文件中的元素列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42633405/

相关文章:

c# - 在 C#/.NET 中将用户名转换为 SID 字符串

xml - PowerShell更新XML元素(内部文本)

javascript - 使用 javascript 处理 Ajax 遇到困难

vb.net - 组加入有多个条件,其中之一是常量

c# - LINQ 计算链接表中的行数

c# - 有没有办法在 C# 中获取两组对象之间的差异

c# - 我可以从我的应用程序中抛出哪些内置 .NET 异常?

c# - 如何从另一个表单按钮启动和暂停后台运行线程?

c# - 性能提示 try/catch block

Android布局在运行时用另一个 View 替换 View