从 XML 中检索属性
为什么运行此代码...
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);
}
在命令提示符中产生以下输出?
<BlackSheep HaveYouAny="Wool" />
0
也就是说,attributes.Count
不应该返回 1 吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当您调用
SelectNodes
< /a> 与“//BaaBaa”返回“BaaBaa”的所有元素。正如您从自己的文档中看到的,BaaBaa 没有属性,它是具有单个属性“HaveYouAny”的“BlackSheep”元素。
如果您想获取子元素的属性计数,则必须在迭代节点时从您所在的节点导航到该子元素。
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
包含元素本身的属性,而不是其子元素的属性。由于
BaaBaa
元素没有任何属性,因此它是空的。InnerXml
属性返回元素内容的 XML,而不是元素本身的 XML。因此,它确实有一个属性。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.解决方案
将产生以下所需的输出
solution
Will produce the following, required output