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

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

870664 次浏览

例如,查看XmlTextReader类。

有很多方法,一些:

    <李> XmlSerializer。使用带有目标模式的类 如果您想读取,请使用XmlSerializer 将Xml中的数据加载到 类的一个实例
  • linq2xml
  • XmlTextReader。
  • XmlDocument
  • XPathDocument(只读访问)

你可以:

示例在msdn页面上提供

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"]是否为空,因为如果属性不存在,它将为空。

Linq to XML.

同时,VB。NET通过编译器提供了比c#更好的xml解析支持。如果你有选择和愿望,来看看。

LINQ to XML例子:

// 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到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()
{
}
}
}

粘贴Bin上的代码 http://pastebin.com/yK7cSNeY < / p >

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字符串。

var xmlString = File.ReadAllText(FILE_PATH);
var stringReader = new StringReader(xmlString);
var dsSet = new DataSet();
dsSet.ReadXml(stringReader);

发布这篇文章是为了提供信息。

有不同的方法,取决于你想去哪里。 XmlDocument比XDocument更轻,但是如果您希望尽可能地验证字符串是否包含XML,那么正则表达式可能是您可以做出的最快、最轻的选择。例如,我已经为我的API实现了SpecFlow烟雾测试,我希望测试任何有效的XML中的一个结果-那么我将使用正则表达式。但是如果我需要从这个XML中提取值,那么我将使用XDocument来解析它,以更快地完成它,并且使用更少的代码。或者我将使用XmlDocument,如果我必须与一个大的XML(有时我与XML的大约1M行,甚至更多);然后我甚至可以一行一行地读它。为什么?尝试在Visual Studio中打开超过800MB的私有字节;即使在生产中,你也不应该有超过2GB的对象。你可以跳电臀舞,但你不应该这么做。如果你必须解析一个包含很多行的文档,那么这个文档可能是CSV。< / p >

我写这条评论,是因为我看到了大量使用XDocument的示例。XDocument不适用于大型文档,或者当您只想验证内容是否为XML有效时。如果希望检查XML本身是否有意义,那么需要Schema。

我对建议的答案也投了反对票,因为我相信它本身就需要上述信息。假设我需要验证200M的XML是否有效,每小时10次。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

免责声明:我是这个库的作者。