本文介绍了如何从 C# 中的 XmlNode 读取属性值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个 XmlNode 并且我想获取名为Name"的属性的值.我该怎么做?

Suppose I have a XmlNode and I want to get the value of an attribute named "Name".How can I do that?

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;

正如评论中所指出的,如果该属性不存在,这将引发异常.安全的方法是:

As pointed out in the comments, this will throw an exception if the attribute doesn't exist. The safe way is:

var attribute = node.Attributes["Name"];
if (attribute != null){
    string employeeName = attribute.Value;
    // Process the value here
}

这篇关于如何从 C# 中的 XmlNode 读取属性值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-15 01:01