如何在 C# 中读取和解析 XML 文件? [英] How do I read and parse an XML file in C#?

查看:37
本文介绍了如何在 C# 中读取和解析 XML 文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 C# 中读取和解析 XML 文件?

How do I read and parse an XML file in C#?

推荐答案

XmlDocument 从字符串或文件中读取 XML.

XmlDocument to read an XML from string or from file.

XmlDocument doc = new XmlDocument();
doc.Load("c:\temp.xml");

doc.LoadXml("<xml>something</xml>");

然后在它下面找到一个节点,就像这样

then find a node below it ie like this

XmlNode node = doc.DocumentElement.SelectSingleNode("/book/title");

foreach(XmlNode node in doc.DocumentElement.ChildNodes){
   string text = node.InnerText; //or loop through its children as well
}

然后像这样读取该节点内的文本

then read the text inside that node like this

string text = node.InnerText;

或读取属性

string attr = node.Attributes["theattributename"]?.InnerText

始终检查 Attributes["something"] 是否为 null,因为如果该属性不存在,它将为 null.

Always check for null on Attributes["something"] since it will be null if the attribute does not exist.

这篇关于如何在 C# 中读取和解析 XML 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆