如何读取和解析C#中的XML文件?
如何读取和解析C#中的XML文件?
XmlDocument从字符串或文件读取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
总是检查属性[“something”]上的空值,因为如果该属性不存在,它将为空。
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);
}
参考 :MSDN上的LINQ to XML
以下是我为阅读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
链接地址: http://www.djcxy.com/p/29919.html