0

我正在使用 System.Xml 在 dotnet/c# 中读取 XmlDocument,我喜欢通过更多属性读取 xmlElement 到更少属性,如何读取?我们可以这样做吗?

我的示例 xml 文件和编码:

<conditions><condition if:size="10pt" if:name="courier"/>
<condition if:size="10pt"/>
<condition if:size="10pt" if:name="times" ifnot:emphasis="bold"/></conditions>

            foreach (XmlElement CondNode in XmlDoc.SelectNodes("//condition"))
{
//how to read and sort(not by length) by no. of attribute

}

我希望阅读以下顺序:

<condition if:size="10pt" if:name="times" ifnot:emphasis="bold"/>
<condition if:size="10pt" if:name="courier"/>
<condition if:size="10pt"/>

提前致谢,

萨兰

4

2 回答 2

0

使用 Linq 转 XML

XDocument doc = XDocument.Parse(xml);
var sorted = doc.Descendants("condition").OrderByDescending(node => node.Attributes().Count());
foreach (XElement condition in sorted)
{
    // Do whatever you need
}
于 2014-04-10T11:35:22.807 回答
0

如果您想继续使用 XmlDocument,您可以像这样对节点进行排序:

var nodes = doc.SelectNodes("//condition")
               .OfType<XmlElement>()
               .OrderByDescending(x => x.Attributes.Count);
foreach (XmlElement CondNode in nodes)
{
     //how to read and sort(not by length) by no. of attribute
}

通过使用OfType<T>您从集合中检索所有 XmlElements(这应该包括集合中的所有节点)并接收一个IEnumerable<XmlElement>作为结果。您可以将其用作 Linq 查询的起点。XmlNodeList仅实现 的非泛型版本,IEnumerable因此您无法在其上运行 Linq 查询,因为大多数方法都是IEnumerable<T>.

于 2014-04-10T11:35:23.000 回答