juan
juan

Reputation: 81964

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, and I'm not sure what would be the optimal way to do it.

Upvotes: 15

Views: 20732

Answers (4)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039378

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");

Upvotes: 13

stephenbayer
stephenbayer

Reputation: 12431

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.

Upvotes: 2

Kurt
Kurt

Reputation: 4517

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.

Upvotes: 1

Gregoire
Gregoire

Reputation: 24872

Use Linq to XML You can see the XDocument class here

Upvotes: 4

Related Questions