views:

63

answers:

2

We are interested in finding maximum number of attributes a node has in a XML document. My code is below using C#:

        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load(@"C:\ABC.xml");
        XmlNode root = xmlDoc.DocumentElement;

        int nodeAttrCount = 0;
        foreach (XmlNode node in root)                            
            if (nodeAttrCount < node.Attributes.Count)
                nodeAttrCount = node.Attributes.Count;

We are interested is: do we have any thing better than this. Like any method or property which give us the same result or anyother option.

A: 

This is three lines of code for a fairly niche requirement. I wouldn't expect this to already exist in the .NET framework.

Your foreach loop looks fine. Are you sure you want to only look at the root elements, and not recurse inside the document?

Tim Robinson
@Tim: We don't need to go recurse inside the document. In fact our XML is like this:<root><file attrib1="" attrib2="" attrib3="" attrib4="" ... />.....</root>sounds Ok?
Malik
Your code looks fine - I'd have written the same thing
Tim Robinson
A: 

You can also use LINQ to XML:

XElement el = XElement.Load("MyXML.xml");
int maxAttr = el.DescendantNodesAndSelf().OfType<XElement>().Max(x => x.Attributes().Count());

The above code traverses all the xml nodes (it works with nested nodes too) and get the maximum number of attributes.


For .net 2.0:

XmlDocument doc = new XmlDocument();
doc.Load("MyXML.xml");
int max = 0;
foreach (XmlNode xmlNode in doc.SelectNodes("//*"))
   if (max < node.Attributes.Count)
       max = node.Attributes.Count;

This is basically the same as your solution; the main difference is that it considers all nodes at every nesting level (using XPath navigation).

digEmAll
Thanks for the code but not working. Gives error '>' as invalid expression. Not recognizing "Max(x => x.Attributes().Count()".
Malik
Mmh really strange, I have just tested the same code and it works fine (I'm targeting .NET 3.5). Do you have "using System.Linq;" in your class header ?
digEmAll
Thanks but our production server is still running .Net 2.0 :(
Malik
OK, since you select mine as the accepted answer, I've added a solution compatible with .net 2.0. ;)
digEmAll
Thanks. Although Tim helped me a lot but I was looking for a solution that is elegent and uptodate. I know that there must be some latest solution out there as age of "loop / traverse manually" :) is over. Thanks again.
Malik