【发布时间】:2010-10-13 03:21:42
【问题描述】:
如何在 C# 中读取和解析 XML 文件?
【问题讨论】:
如何在 C# 中读取和解析 XML 文件?
【问题讨论】:
XmlDocument 从字符串或文件中读取 XML。
using System.Xml;
XmlDocument doc = new XmlDocument();
doc.Load("c:\\temp.xml");
或
doc.LoadXml("<xml>something</xml>");
然后在它下面找到一个节点即这样
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
}
然后像这样读取该节点内的文本
string text = node.InnerText;
或读取一个属性
string attr = node.Attributes["theattributename"]?.InnerText
始终检查 Attributes["something"] 是否为 null,因为如果该属性不存在,它将为 null。
【讨论】:
XmlNode node = XmlDocument.Docu... 行真的是XmlNode = doc.Docu... 吗?为什么答案变了,doc. 被删除了?
这是使用Cinchoo ETL 的另一种方法 - 一个用几行代码解析 xml 文件的开源库。
using (var r = ChoXmlReader<Item>.LoadText(xml)
.WithXPath("//item")
)
{
foreach (var rec in r)
rec.Print();
}
public class Item
{
public string Name { get; set; }
public string ProtectionLevel { get; set; }
public string Description { get; set; }
}
小提琴样例:https://dotnetfiddle.net/otYq5j
免责声明:我是这个库的作者。
【讨论】:
如果您想从 XML 文件中检索特定值
XmlDocument _LocalInfo_Xml = new XmlDocument();
_LocalInfo_Xml.Load(fileName);
XmlElement _XmlElement;
_XmlElement = _LocalInfo_Xml.GetElementsByTagName("UserId")[0] as XmlElement;
string Value = _XmlElement.InnerText;
【讨论】:
// Loading from a file, you can also load from a stream
var xml = XDocument.Load(@"C:\contacts.xml");
// Query the data and write out a subset of contacts
var query = from c in xml.Root.Descendants("contact")
where (int)c.Attribute("id") < 4
select c.Element("firstName").Value + " " +
c.Element("lastName").Value;
foreach (string name in query)
{
Console.WriteLine("Contact's Full Name: {0}", name);
}
参考:LINQ to XML at MSDN
【讨论】:
using System.Xml.Linq; 您将在文档顶部看到相关的命名空间,可从海报链接到的文档页面访问,例如docs.microsoft.com/en-us/dotnet/api/…
有不同的方法,具体取决于您想要到达的位置。 XmlDocument 比 XDocument 轻量级,但如果您希望简单地验证字符串是否包含 XML,那么正则表达式可能是您可以做出的最快和最轻量级的选择。例如,我使用 SpecFlow 为我的 API 实现了冒烟测试,我希望测试其中一个结果是否为任何有效的 XML - 然后我将使用正则表达式。但是,如果我需要从这个 XML 中提取值,那么我会使用 XDocument 对其进行解析,以更快地使用更少的代码来完成它。或者,如果我必须使用大型 XML(有时我使用大约 1M 行的 XML,甚至更多),我会使用 XmlDocument;然后我什至可以逐行阅读。为什么?尝试在 Visual Studio 中打开超过 800MB 的私有字节;即使在生产中,您也不应该拥有大于 2GB 的对象。你可以用twerk,但你不应该。如果您必须解析包含很多行的文档,那么该文档可能是 CSV。
我写了这个评论,因为我看到了很多关于 XDocument 的例子。 XDocument 不适用于大文档,或者当您只想验证内容是否为 XML 有效时。如果您想检查 XML 本身是否有意义,那么您需要 Schema。
我也否决了建议的答案,因为我相信它本身需要上述信息。想象一下,我需要验证 200M 的 XML(每小时 10 次)是否是有效的 XML。 XDocument 会浪费大量资源。
prasanna venkatesh 还指出您可以尝试将字符串填充到数据集,它也会指示有效的 XML。
【讨论】:
您可以使用 DataSet 来读取 XML 字符串。
var xmlString = File.ReadAllText(FILE_PATH);
var stringReader = new StringReader(xmlString);
var dsSet = new DataSet();
dsSet.ReadXml(stringReader);
发布此信息是为了提供信息。
【讨论】:
例如查看XmlTextReader 类。
【讨论】:
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 的构造函数中指定路径名。
【讨论】:
这是我为读取 xml 站点地图编写的应用程序:
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Data;
using System.Xml;
namespace SiteMapReader
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please Enter the Location of the file");
// get the location we want to get the sitemaps from
string dirLoc = Console.ReadLine();
// get all the sitemaps
string[] sitemaps = Directory.GetFiles(dirLoc);
StreamWriter sw = new StreamWriter(Application.StartupPath + @"\locs.txt", true);
// loop through each file
foreach (string sitemap in sitemaps)
{
try
{
// new xdoc instance
XmlDocument xDoc = new XmlDocument();
//load up the xml from the location
xDoc.Load(sitemap);
// cycle through each child noed
foreach (XmlNode node in xDoc.DocumentElement.ChildNodes)
{
// first node is the url ... have to go to nexted loc node
foreach (XmlNode locNode in node)
{
// thereare a couple child nodes here so only take data from node named loc
if (locNode.Name == "loc")
{
// get the content of the loc node
string loc = locNode.InnerText;
// write it to the console so you can see its working
Console.WriteLine(loc + Environment.NewLine);
// write it to the file
sw.Write(loc + Environment.NewLine);
}
}
}
}
catch { }
}
Console.WriteLine("All Done :-)");
Console.ReadLine();
}
static void readSitemap()
{
}
}
}
粘贴箱上的代码 http://pastebin.com/yK7cSNeY
【讨论】:
有很多方法,一些:
【讨论】:
此外,VB.NET 通过编译器对 xml 解析的支持比 C# 好得多。如果您有选择和愿望,check it out.
【讨论】:
【讨论】: