Search code examples
c#.netxmllinqsystem.xml

how to read XmlDocument by maximumn attribute to minimum attribute?


I am reading XmlDocument in dotnet/c#, by using System.Xml, i like to read xmlElement by More attributes to less attribute, how to read? can we do this?

my example xml file and coding:

<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

}

i expect to read below order:

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

Thanks in advance,

Saran


Solution

  • If you want to continue using XmlDocument, you can sort your nodes like this:

    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
    }
    

    By using OfType<T> you retrieve all XmlElements from the collection (this should comprise all nodes in your collection) and receive an IEnumerable<XmlElement> as the result. You can use this as the starting point for Linq queries. XmlNodeList only implements the non-generic version of IEnumerable so that you can't run Linq queries on it as most of the methods are extension methods for IEnumerable<T>.