Retrieving attributes from XML
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'开发者_Go百科t attributes.Count
return 1?
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.
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.
<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
精彩评论