c#中是否有解析XML文件的简单方法?如果有,是什么?
我不确定是否存在“解析XML的最佳实践”。有许多技术适用于不同的情况。使用哪种方式取决于具体的场景。
你可以用LINQ转换成XML、XmlReader、XPathNavigator甚至正则表达式。如果你详细说明你的需求,我可以试着提出一些建议。
使用XmlTextReader, XmlReader, xmlnoderreader和System.Xml.XPath命名空间。和(XPathNavigator, XPathDocument, XPathExpression, XPathnodeIterator)。
通常XPath使XML的阅读更容易,这正是您所追求的。
如果您使用的是。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);
此外,还有一些其他方法可以使用。比如这里。我认为没有一个最好的方法来做到这一点;你总是需要自己选择,什么是最适合你的。
使用好的XSD Schema用XSD .exe创建一组类,使用XmlSerializer用XML创建对象树,反之亦然。如果您对模型的限制很少,您甚至可以尝试使用XML *Attributes在您的模型类和XML之间创建一个直接映射。
在MSDN上有一篇关于XML序列化的介绍性文章。
性能提示:构造XmlSerializer的开销很大。如果您打算解析/写入多个XML文件,请保持对XmlSerializer实例的引用。
如果您正在处理大量数据(许多兆字节),那么您希望使用XmlReader来流解析XML。
其他任何东西(XPathNavigator, XElement, XmlDocument,甚至XmlSerializer,如果您保留完整的生成的对象图)将导致高内存占用和非常慢的加载时间。
当然,如果您无论如何都需要内存中的所有数据,那么您可能没有太多选择。
可以使用ExtendedXmlSerializer进行序列化和反序列化。
Instalation 您可以从nuget安装ExtendedXmlSerializer或运行以下命令:
Install-Package ExtendedXmlSerializer
序列化:
ExtendedXmlSerializer serializer = new ExtendedXmlSerializer();
var obj = new Message();
var xml = serializer.Serialize(obj);
反序列化
var obj2 = serializer.Deserialize<Message>(xml);
. net中的标准XML序列化器非常有限。
不支持具有循环引用的类或具有接口属性的类的序列化, 不支持字典, 没有读取旧版本XML的机制, 如果要创建自定义序列化器,类必须继承自IXmlSerializable。这意味着你的类不是POCO类, 不支持IoC。
ExtendedXmlSerializer可以做到这一点以及更多。
ExtendedXmlSerializer支持。net 4.5或更高版本和。net Core。你可以将它与WebApi和AspCore集成。
您可以使用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);
的文档
我最近被要求处理一个涉及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文件中的任何元素和任何属性了!
推荐文章
- HTTP POST返回错误:417“期望失败。”
- 如何在。net中创建和使用资源
- 为什么Path。以Path.DirectorySeparatorChar开头的文件名合并不正确?
- 如何在c#中获得正确的时间戳
- Linq选择列表中存在的对象(A,B,C)
- c# .NET中的App.config是什么?如何使用它?
- c#:如何获得一个字符串的第一个字符?
- String类中的什么方法只返回前N个字符?
- 更好的方法将对象转换为int类型
- 我可以将c#字符串值转换为转义字符串文字吗?
- 在c#中转换char到int
- c#中朋友的对等物是什么?
- 关键字使用virtual+override vs. new
- 在ASP中选择Tag Helper。NET Core MVC
- 如何在没有任何错误或警告的情况下找到构建失败的原因