2023-09-07 07:00:03

如何解析XML文件?

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


当前回答

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

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

其他回答

我最近被要求处理一个涉及XML文档解析的应用程序,我同意Jon Galloway的观点,基于LINQ to XML的方法在我看来是最好的。然而,我不得不挖掘一些有用的例子,所以闲话少说,这里有一些!

欢迎任何评论,因为这段代码可以工作,但可能不是完美的,我想了解更多关于这个项目的XML解析!

public void ParseXML(string filePath)  
{  
    // create document instance using XML file path
    XDocument doc = XDocument.Load(filePath);

    // get the namespace to that within of the XML (xmlns="...")
    XElement root = doc.Root;
    XNamespace ns = root.GetDefaultNamespace();

    // obtain a list of elements with specific tag
    IEnumerable<XElement> elements = from c in doc.Descendants(ns + "exampleTagName") select c;

    // obtain a single element with specific tag (first instance), useful if only expecting one instance of the tag in the target doc
    XElement element = (from c in doc.Descendants(ns + "exampleTagName" select c).First();

    // obtain an element from within an element, same as from doc
    XElement embeddedElement = (from c in element.Descendants(ns + "exampleEmbeddedTagName" select c).First();

    // obtain an attribute from an element
    XAttribute attribute = element.Attribute("exampleAttributeName");
}

有了这些函数,我就可以解析XML文件中的任何元素和任何属性了!

我不确定是否存在“解析XML的最佳实践”。有许多技术适用于不同的情况。使用哪种方式取决于具体的场景。

你可以用LINQ转换成XML、XmlReader、XPathNavigator甚至正则表达式。如果你详细说明你的需求,我可以试着提出一些建议。

此外,您还可以以以下方式使用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);

的文档

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

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

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

下面是一些例子:

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);

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