質問
このコードを実行しないのはなぜ...
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?
解決
あなたは
SelectNodes
にして呼び出す"// BaaBaa" それは "BaaBaa" のすべての要素を返します。
あなたがあなた自身のドキュメントからもわかるように、BaaBaaが属性はありません。は、それが単一の属性「HaveYouAnyを」持っている「ブラックシープ」要素です。
あなたは子要素の属性数を取得したい場合、あなたはノードを反復処理するときにあるノードからそれにナビゲートする必要があります。
他のヒント
element.Attributes
要素そのものではなく、その子の属性が含まれています。
BaaBaa
要素は、属性を持っていないので、それが空である。
InnerXml
プロパティがない要素自体の、要素の内容のXMLを返します。したがって、それは属性を持っています。
<BlackSheep HaveYouAny=""Wool"" /> // innerXml that includes children
<BaaBaa> // is the only node Loaded, which has '0' attributes
ソリューション
XmlAttributeCollection attributes = element.FirstChild.Attributes;
次のように演出します、必要な出力
<BlackSheep HaveYouAny="Wool" />
1
所属していません StackOverflow