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