tags:

views:

72

answers:

3

Why does running this code...

    XmlDocument doc = new XmlDocument();

    string xml = @"<?xml version=""1.0"" encoding=""utf-8"" ?>
                   <BaaBaa>
                        <BlackSheep HaveYouAny=""Wool"" />  
                   </BaaBaa>";
    doc.LoadXml(xml);

    XmlNodeList nodes = doc.SelectNodes("//BaaBaa");

    foreach (XmlElement element in nodes)
    {
        Console.WriteLine(element.InnerXml);

        XmlAttributeCollection attributes = element.Attributes;
        Console.WriteLine(attributes.Count);
    }

Produce the following output in the command prompt?

<BlackSheep HaveYouAny="Wool" />
0

That is, shouldn't attributes.Count return 1?

+2  A: 

When you call SelectNodes with "//BaaBaa" it returns all elements of "BaaBaa".

As you can see from your own document, BaaBaa has no attributes, it's the "BlackSheep" element that has the single attribute "HaveYouAny".

If you want to get the attribute count of child elements, you have to navigate to that from the node you are on when iterating through the nodes.

casperOne
Cheers. My confusion lay in thinking that doc.SelectNodes("//BaaBaa") would return a node list of the children of "BaaBaa", rather than returning all "BaaBaa" nodes (in this case - just 1 node, which has 0 attributes).
ck
+1  A: 

element.Attributes contains the attributes of the element itself, not its children.

Since the BaaBaa element doesn't have any attributes, it is empty.

The InnerXml property returns the XML of the element's contents, not of the element itself. Therefore, it does have an attribute.

SLaks
A: 
<BlackSheep HaveYouAny=""Wool"" /> // innerXml that includes children
<BaaBaa> // is the only node Loaded, which has '0' attributes 

solution

XmlAttributeCollection attributes = element.FirstChild.Attributes;

Will produce the following, required output

<BlackSheep HaveYouAny="Wool" />
1
Asad Butt