c#中是否有解析XML文件的简单方法?如果有,是什么?
当前回答
如果您正在处理大量数据(许多兆字节),那么您希望使用XmlReader来流解析XML。
其他任何东西(XPathNavigator, XElement, XmlDocument,甚至XmlSerializer,如果您保留完整的生成的对象图)将导致高内存占用和非常慢的加载时间。
当然,如果您无论如何都需要内存中的所有数据,那么您可能没有太多选择。
其他回答
如果你使用的是。net 3.5或更高版本,我会使用LINQ to XML。
我不确定是否存在“解析XML的最佳实践”。有许多技术适用于不同的情况。使用哪种方式取决于具体的场景。
你可以用LINQ转换成XML、XmlReader、XPathNavigator甚至正则表达式。如果你详细说明你的需求,我可以试着提出一些建议。
我最近被要求处理一个涉及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文件中的任何元素和任何属性了!
此外,您还可以以以下方式使用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);
的文档
使用XmlTextReader, XmlReader, xmlnoderreader和System.Xml.XPath命名空间。和(XPathNavigator, XPathDocument, XPathExpression, XPathnodeIterator)。
通常XPath使XML的阅读更容易,这正是您所追求的。
推荐文章
- 新建T()
- 如何将枚举绑定到WPF中的组合框控件?
- 拒绝访问该路径
- Visual Studio - Resx文件默认“内部”为“公共”
- 使用python创建一个简单的XML文件
- 使用linq转换列表到字典,不用担心重复
- 单元测试:日期时间。现在
- 什么是回调?
- 返回匿名类型的结果?
- 何时使用IList,何时使用List
- ConfigurationManager。AppSettings在.NET Core 2.0中可用?
- 在c#的控制台应用程序中使用'async
- 在单元测试中设置HttpContext.Current.Session
- 如何开始开发Internet Explorer扩展?
- 更新行,如果它存在,否则插入逻辑实体框架