在C#中解析XML#
问题描述:
您好,我想知道如何解析C#中的这个简单的XML文件内容。我可以有多个“in”元素,并且可以使用日期,分钟,最大和状态子值。在C#中解析XML#
<out>
<in>
<id>16769</id>
<date>29-10-2010</date>
<now>12</now>
<min>12</min>
<max>23</max>
<state>2</state>
<description>enter text</description>
</in>
<in>
<id>7655</id>
<date>12-10-2010</date>
<now>1</now>
<min>1</min>
<max>2</max>
<state>0</state>
<description>enter text</description>
</in>
</out>
答
您需要System.XML,从XmlDocument.Load(filename)开始。
一旦加载了XmlDocument
,您可以根据需要使用内置的.Net XML对象模型从XmlDocument级别开始深入研究。你可以用一种非常直观的方式递归地走树,在你走的时候从每个XmlNode中捕获你想要的。
或者(最好是)您可以使用XPath - 示例here快速找到匹配某些条件的XmlDocument
中的所有XmlNode
。在C#中使用的示例是XmlNode.SelectNodes。
using System;
using System.IO;
using System.Xml;
public class Sample {
public static void Main() {
XmlDocument doc = new XmlDocument();
doc.Load("booksort.xml");
XmlNodeList nodeList;
XmlNode root = doc.DocumentElement;
nodeList=root.SelectNodes("descendant::book[author/last-name='Austen']");
//Change the price on the books.
foreach (XmlNode book in nodeList)
{
book.LastChild.InnerText="15.95";
}
Console.WriteLine("Display the modified XML document....");
doc.Save(Console.Out);
}
}
答
这可能是超出了你想做,但值得一提...
我讨厌解析XML。说真的,我几乎拒绝这样做,特别是因为.NET可以为我做到这一点。我会做的是创建一个具有上述属性的“In”对象。您可能已经有一个,或者需要60秒才能创建。您还需要一个名为“Out”的In对象列表。
然后只是将XML解串到对象中。这只需要几行代码。这是一个例子。顺便说一句,这使得更改和重新保存数据变得简单。