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

编程入门 行业动态 更新时间:2024-10-11 01:18:10
本文介绍了如何从 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 读取属性值?

本文发布于:2023-11-28 16:21:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1643110.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:属性   XmlNode

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!