문제

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?

도움이 되었습니까?

해결책

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top