【问题标题】:How do I read and parse an XML file in C#?如何在 C# 中读取和解析 XML 文件?
【发布时间】:2010-10-13 03:21:42
【问题描述】:

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

【问题讨论】:

    标签: c# xml


    【解决方案1】:

    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。

    【讨论】:

    • 有效,但 Linq to XML 更好。
    • 虽然你说它“更好”,但这样做比 LINQ 有什么其他缺点吗?就我个人而言,我发现这种方法是最简单的,至少满足我的需要。
    • 我在开始使用 LINQ 之前写了这个。 LINQ 很好,而且可读性更好。这些天我自己主要使用 LINQ。但是有些组件确实需要旧式 XML 对象,所以它仍然会时不时地被使用。我建议您尝试这里的“旧样式”和 LINQ,看看哪种适合您。
    • 不应该XmlNode node = XmlDocument.Docu... 行真的是XmlNode = doc.Docu... 吗?为什么答案变了,doc. 被删除了?
    • @Finglas 在你看来。 :-)
    【解决方案2】:

    这是使用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

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

    【讨论】:

      【解决方案3】:

      如果您想从 XML 文件中检索特定值

       XmlDocument _LocalInfo_Xml = new XmlDocument();
                  _LocalInfo_Xml.Load(fileName);
                  XmlElement _XmlElement;
                  _XmlElement = _LocalInfo_Xml.GetElementsByTagName("UserId")[0] as XmlElement;
                  string Value = _XmlElement.InnerText;
      

      【讨论】:

      【解决方案4】:

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

      参考LINQ to XML at MSDN

      【讨论】:

      • XDocument.Parse("something");对于一个字符串。
      • 不包括在内的人是卑鄙的,谢谢你的回答:)
      • @GabrielGarcia 是的,有时初学者会卡在缺少包含的错误
      • 相关包括哪些内容?
      • using System.Xml.Linq; 您将在文档顶部看到相关的命名空间,可从海报链接到的文档页面访问,例如docs.microsoft.com/en-us/dotnet/api/…
      【解决方案5】:

      有不同的方法,具体取决于您想要到达的位置。 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。

      【讨论】:

        【解决方案6】:

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

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

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

        【讨论】:

        • 很好!这是我发现从 sql xml 列和 .net 共享信息的最快方式!
        • 当您有多个级别时不理想,因为它似乎将每个级别放入数据集中自己的表中。
        • 即使这样也还好。我想这真的取决于你的数据实际上是什么样的,以及你所追求的数据有多少层。
        【解决方案7】:

        例如查看XmlTextReader 类。

        【讨论】:

          【解决方案8】:
            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 的构造函数中指定路径名。

          【讨论】:

            【解决方案9】:

            这是我为读取 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

            【讨论】:

              【解决方案10】:

              有很多方法,一些:

              • XmlSerializer。使用具有目标模式的类 你想阅读 - 使用 XmlSerializer 将 Xml 中的数据加载到 类的一个实例。
              • Linq 2 xml
              • XmlTextReader.
              • XmlDocument
              • XPathDocument(只读访问)

              【讨论】:

              • 实际上,XmlReader.Create 不是直接使用 XmlTextReader,而是从 .NET 2.0 开始。
              【解决方案11】:

              Linq to XML.

              此外,VB.NET 通过编译器对 xml 解析的支持比 C# 好得多。如果您有选择和愿望,check it out.

              【讨论】:

              • “都错了”?不准确,我认为,除非那句话是开玩笑的。 OP没有提供任何信息。关于他工作的 .NET 版本。
              • 嘿,是的。这是开玩笑的,但我不好笑,所以我删除了它。
              【解决方案12】:

              您可以:

              示例在提供的 msdn 页面上

              【讨论】:

                猜你喜欢
                • 2011-04-01
                • 2021-03-21
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多