我有一个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>
我是:
虽然我保存后添加的元素在列表中,但是在保存时它不会保留我在代码中定义的顺序。这是我到目前为止所做的事情(主要是工作有效代码)
//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));
似乎正确排序&#39; Bars&#39;代码中的元素,当我将其保存回文件时,订单不会保留。
有什么想法吗?
答案 0 :(得分:4)
您可以在致电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(...);
的详细信息
答案 1 :(得分:1)
首先,你的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>
你的allBars只是一个节点的集合,它不属于任何节点,所以你需要将它挂在Bars下,我建议先删除那里的所有项目:
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));
doc.Element("FooMgr").Element("Bars").RemoveAll();
doc.Element("FooMgr").Element("Bars").Add(allBars);
答案 2 :(得分:0)
在VB中,这将是
Dim doc As XElement
' to load from a file
'xe = XElement.Load(yourpath)
' for testing
doc = <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>
doc.<Bars>.LastOrDefault.Add(<Bar>
<BarId>101</BarId>
<BarVal>HCESAR</BarVal>
</Bar>)
Dim ie As List(Of XElement) = doc.<Bars>.Elements.OrderBy(Function(el) Integer.Parse(el.<BarId>.Value)).ToList
doc.<Bars>.Elements.Remove()
doc.<Bars>.FirstOrDefault.Add(ie)
' to save file
' doc.Save(yourpath)