按 xml 文件中同一元素的两个属性排序

Sort by two attributes from the same element in an xml file

如何从 xml 文件中的同一元素获取两个属性,比较它们并按数字顺序对它们进行排序?

XML 个元素是:

<Parent>
      <Nice to="647429920" from="20200935" />
      <Nice to="647431008" from="20200969" />
      <Nice to="647432224" from="20201007" />
      <Nice to="647437984" from="20201187" />
      <Nice to="647441632" from="20201301" />
      <Nice to="647441760" from="20201305" />
      <Nice to="647443360" from="20201355" />
      <Nice to="647445728" from="20201429" />
      <Nice to="647446144" from="20201442" />
      <Nice to="647447296" from="20201478" />
      <Nice to="647450400" from="20201575" />
      <Nice to="647450752" from="20201586" />
      <Nice to="647451232" from="20201601" />
</Parent>

我尝试这样做作为获取属性的开始:

foreach (XElement node in xDoc.DocumentElement)
            {
                    Console.Write(node.Element("Nice").Attribute("to").Value);
                    Console.Write(node.Element("Nice").Attribute("from").Value);
                Console.WriteLine(node.Element("Entry").Attribute("from").Value);
            }

这会因 Cast 异常而中断。

编辑:

更新为:

 var xDoc1 = XDocument.Load(xmlPath);
foreach (XElement node in xDoc1.Elements())
{
Console.WriteLine(node.Element("Nice").Attribute("to").Value);
Console.WriteLine(node.Element("Nice").Attribute("from").Value);
}

但是正文中的代码只被读取一次,然后程序退出。它不会遍历整个 xml 文件。

也许您正在尝试将从 'DocumentElement' 返回的 'Xml.XmlElement' 转换为 'Linq.XElement'。
可能你需要这样的东西:

var xDoc = new XmlDocument();
var orderedList = new List<int>();
xDoc.Load(/* xml path */);
var els = xDoc.GetElementsByTagName("Nice").Cast<XmlNode>();
foreach (var el in els)
{
   Console.WriteLine(el.Attributes.Item(0).Value);
   Console.WriteLine(el.Attributes.Item(1).Value);
}

或此代码,如果您想使用 xml.linq
根据@Ed Plunkett 提示编辑

var xDoc1 = XDocument.Load(/* xml path */);
var nodes = xDoc1.Elements("Parent").Elements("Nice");
if(nodes != null && nodes.Any()) 
{
   foreach (XElement node in nodes)
   {
       orderedList.Add(int.Parse(node.Attribute("to").Value));
       orderedList.Add(int.Parse(node.Attribute("from").Value));
   }
}
orderedList.Sort();
foreach (var a in orderedList)
{
   Console.WriteLine(a);
}
Console.ReadLine();

但可能存在一些问题,使用 linq 可以跳过 foreach 循环:

首先,您的值看起来像整数,因此使用 Value 而不将其解析为整数可能会导致问题(IE 比较字符串时 "10" < "2")。

其次,没有检查属性是否存在的空值,会抛出空引用异常。

var xDoc1 = XDocument.Load(/* xml path */);
var nodes = xDoc1.Root.Elements("Nice");

var values = nodes
    .Where(n => n.Attributes().Any(a => a.Name == "to"))
    .Select(n => {
      int result;
      int.TryParse(n.Attributes().First(a => a.Name == "to").Value, out result);
      return result;
    })
    .ToList();

values.AddRange(nodes
    .Where(n => n.Attributes().Any(a => a.Name == "from"))
    .Select(n => {
      int result;
      int.TryParse(n.Attributes().First(a => a.Name == "from").Value, out result);
      return result;
    })
    .ToList());

values = values.OrderBy(n => n).ToList();