如何在c#中读取和解析XML文件?
当前回答
XmlDocument从字符串或文件中读取XML。
using System.Xml;
XmlDocument doc = new XmlDocument();
doc.Load("c:\\temp.xml");
or
doc.LoadXml("<xml>something</xml>");
然后在它下面找到一个节点,就像这样
XmlNode node = doc.DocumentElement.SelectSingleNode("/book/title");
or
foreach(XmlNode node in doc.DocumentElement.ChildNodes){
string text = node.InnerText; //or loop through its children as well
}
然后像这样读取节点内的文本
string text = node.InnerText;
或者读取属性
string attr = node.Attributes["theattributename"]?.InnerText
总是检查Attributes["something"]是否为空,因为如果属性不存在,它将为空。
其他回答
例如,检查XmlTextReader类。
有很多方法,一些:
XmlSerializer。使用带有目标模式的类 如果您想读取,请使用XmlSerializer 将Xml中的数据加载到 类的实例。 linq2xml XmlTextReader。 XmlDocument XPathDocument(只读访问)
public void ReadXmlFile()
{
string path = HttpContext.Current.Server.MapPath("~/App_Data"); // Finds the location of App_Data on server.
XmlTextReader reader = new XmlTextReader(System.IO.Path.Combine(path, "XMLFile7.xml")); //Combines the location of App_Data and the file name
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
break;
case XmlNodeType.Text:
columnNames.Add(reader.Value);
break;
case XmlNodeType.EndElement:
break;
}
}
}
可以避免使用第一个语句,只在XmlTextReader的构造函数中指定路径名。
你可以:
使用XmlSerializer类 使用XmlDocument类
示例在msdn页面上提供
XmlDocument从字符串或文件中读取XML。
using System.Xml;
XmlDocument doc = new XmlDocument();
doc.Load("c:\\temp.xml");
or
doc.LoadXml("<xml>something</xml>");
然后在它下面找到一个节点,就像这样
XmlNode node = doc.DocumentElement.SelectSingleNode("/book/title");
or
foreach(XmlNode node in doc.DocumentElement.ChildNodes){
string text = node.InnerText; //or loop through its children as well
}
然后像这样读取节点内的文本
string text = node.InnerText;
或者读取属性
string attr = node.Attributes["theattributename"]?.InnerText
总是检查Attributes["something"]是否为空,因为如果属性不存在,它将为空。
推荐文章
- 并发HashSet<T>在。net框架?
- 从控制器内获得控制器和动作名称?
- 新建T()
- 如何将枚举绑定到WPF中的组合框控件?
- 拒绝访问该路径
- Visual Studio - Resx文件默认“内部”为“公共”
- 使用python创建一个简单的XML文件
- 使用linq转换列表到字典,不用担心重复
- 单元测试:日期时间。现在
- 什么是回调?
- 返回匿名类型的结果?
- 何时使用IList,何时使用List
- ConfigurationManager。AppSettings在.NET Core 2.0中可用?
- 在c#的控制台应用程序中使用'async
- 在单元测试中设置HttpContext.Current.Session