假设我有一个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>
答案 0 :(得分:185)
试试这个:
string employeeName = chldNode.Attributes["Name"].Value;
答案 1 :(得分:40)
要扩展Konamiman的解决方案(包括所有相关的空检查),这就是我一直在做的事情:
if (node.Attributes != null)
{
var nameAttribute = node.Attributes["Name"];
if (nameAttribute != null)
return nameAttribute.Value;
throw new InvalidOperationException("Node 'Name' not found.");
}
答案 2 :(得分:17)
您可以像处理节点一样遍历所有属性
foreach (XmlNode item in node.ChildNodes)
{
// node stuff...
foreach (XmlAttribute att in item.Attributes)
{
// attribute stuff
}
}
答案 3 :(得分:3)
使用
item.Attributes["Name"].Value;
获得价值。
答案 4 :(得分:3)
如果您只需要名称,请使用xpath。无需自己进行迭代并检查是否为空。
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");
答案 5 :(得分:2)
如果您使用chldNode
作为XmlElement
而不是XmlNode
,则可以使用
var attributeValue = chldNode.GetAttribute("Name");
return value will just be an empty string,以防属性名称不存在。
所以你的循环看起来像这样:
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>
,然后循环遍历它们并读取“名称”属性。
答案 6 :(得分:1)
你也可以使用它;
string employeeName = chldNode.Attributes().ElementAt(0).Name
答案 7 :(得分:1)
又一个解决方案:
string s = "??"; // or whatever
if (chldNode.Attributes.Cast<XmlAttribute>()
.Select(x => x.Value)
.Contains(attributeName))
s = xe.Attributes[attributeName].Value;
当期望的属性attributeName
实际上不存在时,它也避免了异常。