保存按其属性排序的Xml节点

时间:2012-06-18 09:33:15

标签: c# asp.net .net xml sorting

这是我的xml。可以添加新的“项目”节点,我想让所有节点按categoryid排序。

<?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

2 个答案:

答案 0 :(得分: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");

答案 1 :(得分: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);