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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1600065/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 19:14:39  来源:igfitidea点击:

How to read attribute value from XmlNode in C#?

c#.netxml

提问by Ashish Ashu

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

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

XML 文档:

<Root>
    <Employee Name ="TestName">
    <Childs/>
</Root>

采纳答案by Konamiman

Try this:

尝试这个:

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

回答by balexandre

you can loop through all attributes like you do with nodes

您可以像处理节点一样遍历所有属性

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

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

回答by rahul

Use

item.Attributes["Name"].Value;

to get the value.

以获得价值。

回答by Ari Roth

To expand Konamiman's solution (including all relevant null checks), this is what I've been doing:

为了扩展 Konamiman 的解决方案(包括所有相关的空检查),这就是我一直在做的事情:

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

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

回答by an phu

if all you need is the names, use xpath instead. No need to do the iteration yourself and check for null.

如果您只需要名称,请改用 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");

回答by cell-in

You can also use this;

你也可以使用这个;

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

回答by Marco7757

If you use chldNodeas XmlElementinstead of XmlNode, you can use

如果您使用chldNodeasXmlElement而不是XmlNode,则可以使用

var attributeValue = chldNode.GetAttribute("Name");

The return value will just be an empty string, in case the attribute name does not exist.

返回值只是一个空字符串,如果属性名称不存在。

So your loop could look like this:

所以你的循环可能是这样的:

XmlDocument document = new XmlDocument();
var nodes = document.SelectNodes("//Node/N0de/node");

foreach (XmlElement node in nodes)
{
    var attributeValue = node.GetAttribute("Name");
}

This will select all nodes <node>surrounded by <Node><N0de></N0de><Node>tags and subsequently loop through them and read the attribute "Name".

这将选择<node><Node><N0de></N0de><Node>标签包围的所有节点,然后循环遍历它们并读取属性“名称”。

回答by TaW

Yet another solution:

另一个解决方案:

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

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

It also avoids the exception when the expected attribute attributeNameactually doesn't exist.

当预期的属性attributeName实际上不存在时,它还避免了异常。