0

这是我现在的xml。可以添加新的“项目”节点,我希望所有节点都按类别 ID 排序。

<?xml version="1.0" encoding="utf-8"?>
<data>
  <banners>
    <banner type="search-bar">
      <item img="http://site.com/3ac0a.png" id="5df129a6-1" categoryid="7" />
      <item img="http://site.com/3ac1a.png" id="5df129a6-1" categoryid="10" />
      <item img="http://site.com/3ac2a.png" id="dfgsdfgg-1" categoryid="1" />
      <item img="http://site.com/3ac3a.png" id="5erjrthr-1" categoryid="2" />
      <item img="http://site.com/3ac4a.png" id="yuj67445-1" categoryid="3" />
      <item img="http://site.com/3ac5a.png" id="ghjmdmgh-1" categoryid="4" />
    </banner>
  </banners>
</data>

像这样

<?xml version="1.0" encoding="utf-8"?>
<data>
  <banners>
    <banner type="search-bar">
      <item img="http://site.com/3ac2a.png" id="dfgsdfgg-1" categoryid="1" />
      <item img="http://site.com/3ac3a.png" id="5erjrthr-1" categoryid="2" />
      <item img="http://site.com/3ac4a.png" id="yuj67445-1" categoryid="3" />
      <item img="http://site.com/3ac5a.png" id="ghjmdmgh-1" categoryid="4" />
      <item img="http://site.com/3ac0a.png" id="5df129a6-1" categoryid="7" />
      <item img="http://site.com/3ac1a.png" id="5df129a6-1" categoryid="10" />
    </banner>
  </banners>
</data>

我需要保存已排序的 XML

4

2 回答 2

2
XDocument document = XDocument.Parse(xml);
var items = document.Root.Elements("item");
foreach (var item in items)
{
    var elements = item.Elements("item").OrderBy(a => a.Attribute("categoryid").Value).ToArray();
    item.Elements().Remove();
    item.Add(elements);
}

document.Save("your sorted xml path, which you want to save");
于 2012-06-18T09:44:48.133 回答
1
XElement El = XElement.Load(FilePath);
El.Descendants("banner").Where(b => b.Attribute("type").Value == "search-bar").First().ReplaceNodes(
                El.Descendants("banner").Where(b => b.Attribute("type").Value == "search-bar").First().Descendants("item").OrderBy(o => int.Parse(o.Attribute("categoryid").Value)));
            El.Save(FilePath);
于 2012-06-18T10:14:16.980 回答