Best way to manipulate XML in .NET

空扰寡人 提交于 2019-11-27 03:21:14

问题


I need to manipulate an existing XML document, and create a new one from it, removing a few nodes and attributes, and perhaps adding new ones, what would be the best group of classes to accomplish this?

There are a lot of .NET classes for XML manipulation, and I'm not sure what would be the optimal way to do it.


回答1:


If it is a really huge XML which cannot fit into memory you should use XmlReader/XmlWriter. If not LINQ to XML is very easy to use. If you don't have .NET 3.5 you could use XmlDocument.

Here's an example of removing a node:

using System.Xml.Linq;
using System.Xml.XPath;

var doc = XElement.Load("test.xml");
doc.XPathSelectElement("//customer").Remove();
doc.Save("test.xml");



回答2:


Use Linq to XML You can see the XDocument class here




回答3:


Parsing the document with XML Style Sheets might be the easiest option if it is just a conversion process.

Here is how to use XSLT in .NET.

and

Here is an introduction to XSLT.

It confused me a bit at first, but now I pretty much use XSLT to do all my XML conversions.




回答4:


If you have an official schema, you can use the XmlSerializer. Otherwise it is best to use the XmlDocument, XmlNode, XmlElement etc classes.

Otherwise it could also depend on what you are using the xml for, i.e. marking up some document, representing objects etc.



来源:https://stackoverflow.com/questions/2470103/best-way-to-manipulate-xml-in-net

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!