假设我有一个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)
{
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
XML文档:
<Root>
<Employee Name ="TestName">
<Childs/>
</Root>
Run Code Online (Sandbox Code Playgroud)
Kon*_*man 200
试试这个:
string employeeName = chldNode.Attributes["Name"].Value;
Run Code Online (Sandbox Code Playgroud)
Ari*_*oth 42
要扩展Konamiman的解决方案(包括所有相关的空检查),这就是我一直在做的事情:
if (node.Attributes != null)
{
var nameAttribute = node.Attributes["Name"];
if (nameAttribute != null)
return nameAttribute.Value;
throw new InvalidOperationException("Node 'Name' not found.");
}
Run Code Online (Sandbox Code Playgroud)
bal*_*dre 17
您可以循环遍历所有属性,就像使用节点一样
foreach (XmlNode item in node.ChildNodes)
{
// node stuff...
foreach (XmlAttribute att in item.Attributes)
{
// attribute stuff
}
}
Run Code Online (Sandbox Code Playgroud)
如果您使用chldNodeasXmlElement而不是XmlNode,则可以使用
var attributeValue = chldNode.GetAttribute("Name");
Run Code Online (Sandbox Code Playgroud)
该返回值只是一个空字符串,如果属性名称不存在。
所以你的循环可能是这样的:
XmlDocument document = new XmlDocument();
var nodes = document.SelectNodes("//Node/N0de/node");
foreach (XmlElement node in nodes)
{
var attributeValue = node.GetAttribute("Name");
}
Run Code Online (Sandbox Code Playgroud)
这将选择<node>被<Node><N0de></N0de><Node>标签包围的所有节点,然后循环遍历它们并读取属性“名称”。