0

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

saravanan s
  • 175
  • 3
  • 14

2 Answers2

0

using 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
}
voidengine
  • 2,504
  • 1
  • 17
  • 29
0

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

Markus
  • 20,838
  • 4
  • 31
  • 55