XmlNodeがあり、「Name」という名前の属性の値を取得するとします。どうやってやるの?
XmlTextReader reader = new XmlTextReader(path);
XmlDocument doc = new XmlDocument();
XmlNode node = doc.ReadNode(reader);
foreach (XmlNode chldNode in node.ChildNodes)
{
**//Read the attribute Name**
if (chldNode.Name == Employee)
{
if (chldNode.HasChildNodes)
{
foreach (XmlNode item in node.ChildNodes)
{
}
}
}
}
XMLドキュメント:
<Root>
<Employee Name ="TestName">
<Childs/>
</Root>
これを試して:
string employeeName = chldNode.Attributes["Name"].Value;
コナミマンのソリューション(関連するすべてのnullチェックを含む)を拡張するために、これは私がやっていることです:
if (node.Attributes != null)
{
var nameAttribute = node.Attributes["Name"];
if (nameAttribute != null)
return nameAttribute.Value;
throw new InvalidOperationException("Node 'Name' not found.");
}
ノードと同じように、すべての属性をループできます
foreach (XmlNode item in node.ChildNodes)
{
// node stuff...
foreach (XmlAttribute att in item.Attributes)
{
// attribute stuff
}
}
名前だけが必要な場合は、代わりにxpathを使用します。自分で繰り返しを行ってnullをチェックする必要はありません。
string xml = @"
<root>
<Employee name=""an"" />
<Employee name=""nobyd"" />
<Employee/>
</root>
";
var doc = new XmlDocument();
//doc.Load(path);
doc.LoadXml(xml);
var names = doc.SelectNodes("//Employee/@name");
つかいます
item.Attributes["Name"].Value;
値を取得します。
chldNode
の代わりにXmlElement
としてXmlNode
を使用する場合、次を使用できます。
var attributeValue = chldNode.GetAttribute("Name");
戻り値は空の文字列になります 、属性名が存在しない場合。
したがって、ループは次のようになります。
XmlDocument document = new XmlDocument();
var nodes = document.SelectNodes("//Node/N0de/node");
foreach (XmlElement node in nodes)
{
var attributeValue = node.GetAttribute("Name");
}
これにより、<node>
タグで囲まれたすべてのノード<Node><N0de></N0de><Node>
が選択され、その後それらをループして属性「名前」を読み取ります。
さらに別のソリューション:
string s = "??"; // or whatever
if (chldNode.Attributes.Cast<XmlAttribute>()
.Select(x => x.Value)
.Contains(attributeName))
s = xe.Attributes[attributeName].Value;
また、期待される属性attributeName
が実際に存在しない場合の例外を回避します。
これも使用できます。
string employeeName = chldNode.Attributes().ElementAt(0).Name