如何从C#中的XmlNode读取属性值?

Ash*_*shu 107 .net c# xml

假设我有一个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)

  • 小心这种方法.我认为如果该属性不存在,那么访问Value成员将导致Null引用异常. (32认同)
  • @Omidoo这种方法有同样的问题,例如`<ax ="1"/>`,它通过了测试.也许类似于`var attr = node.Attributes ["Name"]; if(attr!= null){...}`可能有用. (6认同)
  • if(node.Attributes!= null)string employeeName = chldNode.Attributes ["Name"].Value; (3认同)

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)

  • 没有得到空值错误的简便方法是node.Attributes?["Name"]?.Value (6认同)

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)


Mar*_*757 5

如果您使用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>标签包围的所有节点,然后循环遍历它们并读取属性“名称”。