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

C# 如何在C中读取和解析XML文件?,c#,xml,C#,Xml,如何读取和解析C语言中的XML文件?例如,签出类。有很多方法,有些方法: XmlSerializer。使用具有目标架构的类 您想要读取-使用XmlSerializer 将Xml中的数据加载到 类的实例。 linq2xml XmlTextReader。 XML文档 XPathDocument只读访问 您可以: 使用 使用 示例见提供的msdn页面XmlDocument,用于从字符串或文件中读取XML XmlDocument doc = new XmlDocument(); doc.Load("c:

如何读取和解析C语言中的XML文件?

例如,签出类。

有很多方法,有些方法:

XmlSerializer。使用具有目标架构的类 您想要读取-使用XmlSerializer 将Xml中的数据加载到 类的实例。 linq2xml XmlTextReader。 XML文档 XPathDocument只读访问 您可以:

使用 使用
示例见提供的msdn页面

XmlDocument,用于从字符串或文件中读取XML

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

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

XmlNode node = doc.DocumentElement.SelectSingleNode("/book/title");
string text = node.InnerText;
或者读取属性

string attr = node.Attributes["theattributename"]?.InnerText
始终检查属性[something]是否为null,因为如果该属性不存在,则该属性将为null

此外,VB.NET通过编译器提供的xml解析支持比C好得多。如果您有选择和愿望,请参见示例:
参考:在MSDN上,我编写了一个用于阅读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()
        {
        }
    }
}
粘贴箱上的代码


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

可以使用数据集读取XML字符串

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

发布此消息是为了获取信息

有不同的方法,取决于你想去哪里。 XmlDocument比XDocument轻,但是如果您希望最低限度地验证字符串是否包含XML,那么正则表达式可能是您可以做出的最快、最轻的选择。例如,我已经用SpecFlow为我的API实现了烟雾测试,我希望测试其中一个结果是否为任何有效的XML,然后我将使用正则表达式。但是,如果我需要从这个XML中提取值,那么我将使用XDocument对其进行解析,以更快、更少的代码完成。或者,如果我必须处理一个大的XML,我会使用XmlDocument,有时我处理的XML大约有一百万行,甚至更多;然后我甚至可以一行一行地读。为什么?尝试在VisualStudio中打开超过800MB的专用字节;即使在生产环境中,也不应该有大于2GB的对象。你可以用短发,但不应该。如果您必须解析一个包含很多行的文档,那么这个文档可能是CSV

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

我还否决了建议的答案,因为我认为它本身需要上述信息。假设我需要验证每小时10次的2亿XML是否是有效的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;

全错了?我认为这并不准确,除非那句话是开玩笑的。OP没有提供任何信息。关于他工作的.NET版本。嘿,是的。这是开玩笑的,但我并不好笑,所以我删除了它。事实上,XmlReader.Create代替了直接使用XmlTextReader,因为.NET 2.0.0是有效的,但是Linq到XML要好得多。虽然你说它“更好”,但通过Linq这样做还有其他缺点吗?就我个人而言,我发现这个方法是最简单的,至少对于我的需求来说是这样的。LINQ很好,可读性也比较好。这些天我自己主要使用LINQ。但是有些组件确实需要老式的XML对象,所以它仍然时不时地被使用。我建议您尝试一下这里的旧样式和LINQ,看看什么适合您。。。行是否真的是XmlNode=doc.Docu。。。?为什么答案变了,医生也变了。删除?是的。我不知道为什么我改变了。。。将修复.XDocument.Parsesomething;对于字符串来说,不包含include的人是卑鄙的,谢谢你的回答:@GabrielGarcia true,有时初学者会陷入缺少include的错误中,相关的include是什么?使用System.Xml.Linq;您将在文档顶部看到相关名称空间,可从海报链接的文档页面访问,例如,非常好!这是我发现的共享SQLXML列和.net中的信息的最快方法!!当您有多个级别时,这并不理想,因为它似乎将每个级别放在数据集中自己的表中。即使如此,这也很好。我想这真的取决于你的数据实际上是什么样子的,以及你所追求的数据有多深。这和你所使用的技术是一样的。
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()
        {
        }
    }
}
  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;
            }
        }
    }
var xmlString = File.ReadAllText(FILE_PATH);
var stringReader = new StringReader(xmlString);
var dsSet = new DataSet();
dsSet.ReadXml(stringReader);
 XmlDocument _LocalInfo_Xml = new XmlDocument();
            _LocalInfo_Xml.Load(fileName);
            XmlElement _XmlElement;
            _XmlElement = _LocalInfo_Xml.GetElementsByTagName("UserId")[0] as XmlElement;
            string Value = _XmlElement.InnerText;