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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/642293/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 11:28:33  来源:igfitidea点击:

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

c#xml

提问by Gajendra

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

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

回答by Frederik Gheysels

Check out XmlTextReaderclass for instance.

例如,查看XmlTextReader类。

回答by eglasius

There are lots of way, some:

有很多方法,一些:

  • XmlSerializer. use a class with the target schema you want to read - use XmlSerializer to get the data in an Xml loaded into an instance of the class.
  • Linq 2 xml
  • XmlTextReader.
  • XmlDocument
  • XPathDocument (read-only access)
  • XmlSerializer。使用具有您想要读取的目标架构的类 - 使用 XmlSerializer 将 Xml 中的数据加载到类的实例中。
  • Linq 2 xml
  • XmlTextReader。
  • 文档
  • XPathDocument(只读访问)

回答by Grzenio

You can either:

您可以:

Examples are on the msdn pages provided

示例在提供的 msdn 页面上

回答by Wolf5

XmlDocument to read an XML from string or from file.

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

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

or

或者

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

then find a node below it ie like this

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

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
}

then read the text inside that node like this

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

string text = node.InnerText;

or read an attribute

或读取属性

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

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

始终检查 Attributes["something"] 上的 null,因为如果该属性不存在,它将为 null。

回答by Wolf5

Linq to XML.

LINQ 到 XML。

Also, VB.NET has much better xml parsing support via the compiler than C#. If you have the option and the desire, check it out.

此外,与 C# 相比,VB.NET 通过编译器提供了更好的 xml 解析支持。如果您有选择和愿望,请检查一下。

回答by Konstantin Tarkus

LINQ to XMLExample:

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);
}

Reference: LINQ to XMLat MSDN

参考:MSDN 上的LINQ to XML

回答by ajzeffer

Here's an application I wrote for reading xml sitemaps:

这是我为读取 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()
        {
        }
    }
}

Code on Paste Bin http://pastebin.com/yK7cSNeY

粘贴箱上的代码 http://pastebin.com/yK7cSNeY

回答by Vishal Kotak

  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;
            }
        }
    }

You can avoid the first statement and just specify the path name in constructor of XmlTextReader.

您可以避免使用第一条语句,只需在 XmlTextReader 的构造函数中指定路径名。

回答by prasanna venkatesh

You could use a DataSet to read XML strings.

您可以使用 DataSet 来读取 XML 字符串。

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

Posting this for the sake of information.

发布此信息是为了提供信息。

回答by nkalfov

There are different ways, depending on where you want to get. XmlDocument is lighter than XDocument, but if you wish to verify minimalistically that a string contains XML, then regular expression is possibly the fastest and lightest choice you can make. For example, I have implemented Smoke Tests with SpecFlow for my API and I wish to test if one of the results in any valid XML - then I would use a regular expression. But if I need to extract values from this XML, then I would parse it with XDocument to do it faster and with less code. Or I would use XmlDocument if I have to work with a big XML (and sometimes I work with XML's that are around 1M lines, even more); then I could even read it line by line. Why? Try opening more than 800MB in private bytes in Visual Studio; even on production you should not have objects bigger than 2GB. You can with a twerk, but you should not. If you would have to parse a document, which contains A LOT of lines, then this documents would probably be CSV.

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

I have written this comment, because I see a lof of examples with XDocument. XDocument is not good for big documents, or when you only want to verify if there the content is XML valid. If you wish to check if the XML itself makes sense, then you need Schema.

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

I also downvoted the suggested answer, because I believe it needs the above information inside itself. Imagine I need to verify if 200M of XML, 10 times an hour, is valid XML. XDocument will waste a lof of resources.

我也拒绝了建议的答案,因为我相信它本身需要上述信息。想象一下,我需要验证 200M 的 XML(每小时 10 次)是否是有效的 XML。XDocument 会浪费大量资源。

prasanna venkatesh also states you could try filling the string to a dataset, it will indicate valid XML as well.

prasanna venkatesh 还指出您可以尝试将字符串填充到数据集,它也将指示有效的 XML。