2009-10-21 103 views
84

假设我得到一个XmlNode,并且我想为attirbute“Name”赋值。 我该怎么做?如何从C#中的XmlNode读取属性值?

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> 

回答

154

试试这个:

string employeeName = chldNode.Attributes["Name"].Value; 
+27

请小心使用此方法。我认为如果该属性不存在,那么访问Value成员将导致一个空引用异常。 – 2009-10-21 14:06:15

+2

if(node.Attributes!= null) string employeeName = chldNode.Attributes [“Name”]。Value; – Omidoo 2012-09-28 23:03:35

+5

@Omidoo该方法具有相同的问题,例如通过测试的''。也许像'var attr = node.Attributes [“Name”];如果(attr!= null){...}'可能有效。 – Nenotlep 2012-11-13 12:00:51

17

您可以通过所有属性循环像你这样的节点

foreach (XmlNode item in node.ChildNodes) 
{ 
    // node stuff... 

    foreach (XmlAttribute att in item.Attributes) 
    { 
     // attribute stuff 
    } 
} 
+0

这将是更可取的.. :) – 2017-02-27 05:39:31

3

确实使用

item.Attributes["Name"].Value; 

得到值

36

扩大Konamiman的解决方案(包括所有相关null检查),这是我一直在做:

if (node.Attributes != null) 
{ 
    var nameAttribute = node.Attributes["Name"]; 
    if (nameAttribute != null) 
     return nameAttribute.Value; 

    throw new InvalidOperationException("Node 'Name' not found."); 
} 
+2

没有得到空值错误的简写方法是node.Attributes?[“Name”] ?.值 – brandonstrong 2017-03-02 19:51:48

+1

也是如此,尽管我唯一要指出的是,虽然你可以在一行中做到这一点(使它适用于任务或某事),但在抛出异常时控制方面的灵活性稍差否则处理节点没有属性的情况。 – 2017-03-03 00:28:23

+1

同意。任何使用简写方式的人都应该确保它不会导致下游问题。 – brandonstrong 2017-03-03 20:13:57

3

,如果你需要的是名字,使用的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"); 
+0

上述方法不适用于我的XML(尽管我希望他们有)。这个方法确实!谢谢! – Frecklefoot 2015-06-23 21:41:06

1

你也可以用这个;

string employeeName = chldNode.Attributes().ElementAt(0).Name 
2

如果使用chldNodeXmlElement,而不是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><N0de></N0de><Node>标签包围的所有节点<node>,随后依次通过他们,并读取属性“名称”。

1

又一解决方案:

string s = "??"; // or whatever 

if (chldNode.Attributes.Cast<XmlAttribute>() 
         .Select(x => x.Value) 
         .Contains(attributeName)) 
    s = xe.Attributes[attributeName].Value; 

它也避免了当预期属性attributeName实际上不存在例外。