【问题标题】:how to read XmlDocument by maximumn attribute to minimum attribute?如何通过最大属性读取 XmlDocument 到最小属性?
【发布时间】:2014-05-24 01:31:24
【问题描述】:

我正在读取 dotnet/c# 中的 XmlDocument,通过使用 System.Xml,我喜欢通过更多属性读取 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"/>

提前致谢,

萨兰

【问题讨论】:

    标签: c# .net xml linq system.xml


    【解决方案1】:

    使用 Linq to 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
    }
    

    【讨论】:

    • 嗨 pjotr,非常感谢您的大力帮助和我的期望
    【解决方案2】:

    如果您想继续使用 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&lt;T&gt;,您可以从集合中检索所有XmlElement(这应该包括集合中的所有节点)并收到IEnumerable&lt;XmlElement&gt; 作为结果。您可以将其用作 Linq 查询的起点。 XmlNodeList 仅实现了IEnumerable 的非泛型版本,因此您无法对其运行 Linq 查询,因为大多数方法都是 IEnumerable&lt;T&gt; 的扩展方法。

    【讨论】:

    • 嗨,Markus,非常感谢您的大力帮助和我的期望
    • 嗨,Markus,我还有一个疑问,我可以只计算命名空间属性来进行排序吗?谢谢
    • @saravanans:如果您只想在排序时使用特定的命名空间前缀,您可以尝试以下操作:.OrderByDescending(x =&gt; x.Attributes.OfType&lt;XmlAttribute&gt;().Where(a =&gt; a.Prefix == "if").Count());
    • 感谢您的宝贵时间!它工作正常。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-23
    • 1970-01-01
    相关资源
    最近更新 更多