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

Gaj*_*dra 340 c# xml

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

Wol*_*lf5 454

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

XmlDocument doc = new XmlDocument();
doc.Load("c:\\temp.xml");
Run Code Online (Sandbox Code Playgroud)

要么

doc.LoadXml("<xml>something</xml>");
Run Code Online (Sandbox Code Playgroud)

然后找到它下面的节点,就像这样

XmlNode node = doc.DocumentElement.SelectSingleNode("/book/title");
Run Code Online (Sandbox Code Playgroud)

要么

foreach(XmlNode node in doc.DocumentElement.ChildNodes){
   string text = node.InnerText; //or loop through its children as well
}
Run Code Online (Sandbox Code Playgroud)

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

string text = node.InnerText;
Run Code Online (Sandbox Code Playgroud)

或读取属性

string attr = node.Attributes["theattributename"]?.InnerText
Run Code Online (Sandbox Code Playgroud)

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

  • 在我开始使用LINQ之前,我写过这个.LINQ很好,可以更容易阅读.我这些天大部分时间都在使用LINQ.但是有些组件确实需要旧式XML对象,因此它仍然会被使用.我建议尝试这里的"旧式"和LINQ,看看适合你的是什么. (6认同)
  • 虽然你说它"更好"但是在LINQ上这样做有什么其他的缺点吗?就个人而言,我发现这种方法最简单,至少对我的需求而言. (3认同)

Kon*_*kus 206

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);
}
Run Code Online (Sandbox Code Playgroud)

参考:MSDN上的LINQ to XML

  • XDocument.Parse( "<XML>东西</ XML>"); 一个字符串. (15认同)
  • 不包含在内的人很卑鄙,谢谢你的回答:) (5认同)
  • 相关内容包括哪些? (2认同)

ajz*_*fer 16

这是我为阅读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()
        {
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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


egl*_*ius 11

有很多方法,一些:

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

  • 实际上,XmlReader.Create而不是直接使用XmlTextReader,因为.NET 2.0. (2认同)

Grz*_*nio 7

你可以:

示例在提供的msdn页面上


小智 7

Linq to XML.

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

  • 呵呵,是的。这是在开玩笑,但我并不好笑,所以我删除了它。 (2认同)

小智 7

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

var xmlString = File.ReadAllText(FILE_PATH);
var stringReader = new StringReader(xmlString);
var dsSet = new DataSet();
dsSet.ReadXml(stringReader);
Run Code Online (Sandbox Code Playgroud)

发布此信息以供参考.