2023-09-07 07:00:03

如何解析XML文件?

c#中是否有解析XML文件的简单方法?如果有,是什么?


当前回答

如果您使用的是。net 2.0,请尝试XmlReader及其子类XmlTextReader和XmlValidatingReader。它们提供了一种快速、轻量级(内存使用等)、仅向前的方法来解析XML文件。

如果需要XPath功能,请尝试XPathNavigator。如果您需要内存中的整个文档,请尝试XmlDocument。

其他回答

此外,您还可以以以下方式使用XPath选择器(简单地选择特定节点):

XmlDocument doc = new XmlDocument();
doc.Load("test.xml");

var found = doc.DocumentElement.SelectNodes("//book[@title='Barry Poter']"); // select all Book elements in whole dom, with attribute title with value 'Barry Poter'

// Retrieve your data here or change XML here:
foreach (XmlNode book in nodeList)
{
  book.InnerText="The story began as it was...";
}

Console.WriteLine("Display XML:");
doc.Save(Console.Out);

的文档

使用好的XSD Schema用XSD .exe创建一组类,使用XmlSerializer用XML创建对象树,反之亦然。如果您对模型的限制很少,您甚至可以尝试使用XML *Attributes在您的模型类和XML之间创建一个直接映射。

在MSDN上有一篇关于XML序列化的介绍性文章。

性能提示:构造XmlSerializer的开销很大。如果您打算解析/写入多个XML文件,请保持对XmlSerializer实例的引用。

这很简单。我知道这些都是标准方法,但是您可以创建自己的库来更好地处理这些方法。

下面是一些例子:

XmlDocument xmlDoc= new XmlDocument(); // Create an XML document object
xmlDoc.Load("yourXMLFile.xml"); // Load the XML document from the specified file

// Get elements
XmlNodeList girlAddress = xmlDoc.GetElementsByTagName("gAddress");
XmlNodeList girlAge = xmlDoc.GetElementsByTagName("gAge"); 
XmlNodeList girlCellPhoneNumber = xmlDoc.GetElementsByTagName("gPhone");

// Display the results
Console.WriteLine("Address: " + girlAddress[0].InnerText);
Console.WriteLine("Age: " + girlAge[0].InnerText);
Console.WriteLine("Phone Number: " + girlCellPhoneNumber[0].InnerText);

此外,还有一些其他方法可以使用。比如这里。我认为没有一个最好的方法来做到这一点;你总是需要自己选择,什么是最适合你的。

如果你使用的是。net 3.5或更高版本,我会使用LINQ to XML。

使用XmlTextReader, XmlReader, xmlnoderreader和System.Xml.XPath命名空间。和(XPathNavigator, XPathDocument, XPathExpression, XPathnodeIterator)。

通常XPath使XML的阅读更容易,这正是您所追求的。