c#中是否有解析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文件中的任何元素和任何属性了!
其他回答
如果你使用的是。net 3.5或更高版本,我会使用LINQ to XML。
我不确定是否存在“解析XML的最佳实践”。有许多技术适用于不同的情况。使用哪种方式取决于具体的场景。
你可以用LINQ转换成XML、XmlReader、XPathNavigator甚至正则表达式。如果你详细说明你的需求,我可以试着提出一些建议。
您可以使用XmlDocument,为了从属性中操作或检索数据,您可以Linq到XML类。
如果您使用的是。net 2.0,请尝试XmlReader及其子类XmlTextReader和XmlValidatingReader。它们提供了一种快速、轻量级(内存使用等)、仅向前的方法来解析XML文件。
如果需要XPath功能,请尝试XPathNavigator。如果您需要内存中的整个文档,请尝试XmlDocument。
可以使用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集成。
推荐文章
- 实体框架核心:在上一个操作完成之前,在此上下文中开始的第二个操作
- 如何为构造函数定制Visual Studio的私有字段生成快捷方式?
- 如何使用JSON确保字符串是有效的JSON。网
- AppSettings从.config文件中获取值
- 通过HttpClient向REST API发布一个空体
- 如何检查IEnumerable是否为空或空?
- 自动化invokerrequired代码模式
- 在c#代码中设置WPF文本框的背景颜色
- 在c#中,什么是单子?
- c#和Java中的泛型有什么不同?和模板在c++ ?
- c#线程安全快速(est)计数器
- 如何将此foreach代码转换为Parallel.ForEach?
- 如何分裂()一个分隔字符串到一个列表<字符串>
- 如何转换列表<字符串>列表<int>?
- c#对象列表,我如何得到一个属性的和