Best way to manipulate XML in .NET
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, a开发者_开发百科nd I'm not sure what would be the optimal way to do it.
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");
Use Linq to XML You can see the XDocument class here
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.
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.
精彩评论