在C#中读取和解析XML文件,可以使用.NET框架自带的XmlReader类或者LINQ to XML。下面是两种方法的示例代码:
using System;
using System.IO;
using System.Xml;
public class XmlReaderExample
{
public static void Main()
{
try
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.DtdProcessing = DtdProcessing.Parse;
XmlReader reader = XmlReader.Create("example.xml", settings);
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
Console.WriteLine("Element: " + reader.Name);
break;
case XmlNodeType.Text:
Console.WriteLine("Text: " + reader.Value);
break;
case XmlNodeType.EndElement:
Console.WriteLine("End Element: " + reader.Name);
break;
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
using System;
using System.Xml.Linq;
public class LinqToXmlExample
{
public static void Main()
{
try
{
XDocument doc = XDocument.Load("example.xml");
var query = from item in doc.Descendants("item")
select new
{
Title = item.Element("title").Value,
Description = item.Element("description").Value
};
foreach (var i in query)
{
Console.WriteLine("Title: {0}, Description: {1}", i.Title, i.Description);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
这两种方法都可以读取和解析XML文件,根据实际需求选择合适的方法。
领取专属 10元无门槛券
手把手带您无忧上云