[英]How do I read and parse an XML file in C#?
如何在 C# 中读取和解析 XML 文件?
XmlDocument 从字符串或文件中读取 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。
// 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);
}
参考:MSDN 上的LINQ to XML
这是我为读取 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
有很多方法,一些:
您可以使用 DataSet 来读取 XML 字符串。
var xmlString = File.ReadAllText(FILE_PATH);
var stringReader = new StringReader(xmlString);
var dsSet = new DataSet();
dsSet.ReadXml(stringReader);
发布此信息是为了提供信息。
此外,与 C# 相比,VB.NET 通过编译器提供了更好的 xml 解析支持。 如果您有选择和愿望, 请检查一下。
例如,查看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 的构造函数中指定路径名。
有不同的方式,这取决于你想要到达的地方。 XmlDocument 比 XDocument 更轻量,但如果您希望以最少的方式验证字符串是否包含 XML,那么正则表达式可能是您可以做出的最快、最轻量的选择。 例如,我已经为我的 API 实现了带有 SpecFlow 的烟雾测试,我希望测试结果之一是否在任何有效的 XML 中 - 然后我将使用正则表达式。 但是如果我需要从这个 XML 中提取值,那么我会用 XDocument 解析它以更快地完成它并使用更少的代码。 或者,如果我必须使用大型 XML,我将使用 XmlDocument(有时我使用大约 100 万行的 XML,甚至更多); 然后我什至可以一行一行地阅读它。 为什么? 尝试在 Visual Studio 中打开超过 800MB 的私有字节; 即使在生产中,您也不应该拥有大于 2GB 的对象。 你可以用 twerk,但你不应该。 如果您必须解析包含很多行的文档,那么该文档可能是 CSV。
我写了这个评论,因为我看到了很多 XDocument 的例子。 XDocument 不适用于大文档,或者当您只想验证内容是否为 XML 有效时。 如果您想检查 XML 本身是否有意义,那么您需要 Schema。
我也拒绝了建议的答案,因为我相信它本身需要上述信息。 想象一下,我需要验证 200M 的 XML(每小时 10 次)是否是有效的 XML。 XDocument 会浪费大量资源。
prasanna venkatesh 还指出您可以尝试将字符串填充到数据集,它也将指示有效的 XML。
如果要从 XML 文件中检索特定值
XmlDocument _LocalInfo_Xml = new XmlDocument();
_LocalInfo_Xml.Load(fileName);
XmlElement _XmlElement;
_XmlElement = _LocalInfo_Xml.GetElementsByTagName("UserId")[0] as XmlElement;
string Value = _XmlElement.InnerText;
这是使用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
免责声明:我是这个库的作者。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.