2023-09-07 07:00:03

如何解析XML文件?

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


当前回答

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

下面是一些例子:

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

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

其他回答

您可以使用XmlDocument,为了从属性中操作或检索数据,您可以Linq到XML类。

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

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

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

如果您正在处理大量数据(许多兆字节),那么您希望使用XmlReader来流解析XML。

其他任何东西(XPathNavigator, XElement, XmlDocument,甚至XmlSerializer,如果您保留完整的生成的对象图)将导致高内存占用和非常慢的加载时间。

当然,如果您无论如何都需要内存中的所有数据,那么您可能没有太多选择。

您可以使用System.Xml.Linq库解析XML。下面是我用来解析XML文件的示例代码

public CatSubCatList GenerateCategoryListFromProductFeedXML()
{
    string path = System.Web.HttpContext.Current.Server.MapPath(_xmlFilePath);

    XDocument xDoc = XDocument.Load(path);

    XElement xElement = XElement.Parse(xDoc.ToString());


    List<Category> lstCategory = xElement.Elements("Product").Select(d => new Category
    {
        Code = Convert.ToString(d.Element("CategoryCode").Value),
        CategoryPath = d.Element("CategoryPath").Value,
        Name = GetCateOrSubCategory(d.Element("CategoryPath").Value, 0), // Category
        SubCategoryName = GetCateOrSubCategory(d.Element("CategoryPath").Value, 1) // Sub Category
    }).GroupBy(x => new { x.Code, x.SubCategoryName }).Select(x => x.First()).ToList();

    CatSubCatList catSubCatList = GetFinalCategoryListFromXML(lstCategory);

    return catSubCatList;
}

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

的文档