XmlDocument vs XDocument Example and comparison
suggest changeThere are several ways to interact with an XML file.
- XmlDocument
- XDocument
- XmlReader/XmlWriter
Before LINQ to XML, we used XmlDocument for manipulations in XML, such as adding attributes, elements, and so on. Now LINQ to XML uses XDocument for the same kind of thing. The syntax is much easier than XmlDocument and it requires a minimal amount of code.
Also XDocument is much faster than XmlDocument. XmlDocument is an old and dirty solution for querying an XML document.
I am going to show some examples of XmlDocument class and XDocument class:
Load XML file
string filename = @"C:\temp\test.xml";
XmlDocument
XmlDocument _doc = new XmlDocument();
_doc.Load(filename);
XDocument
XDocument _doc = XDocument.Load(fileName);
Create XmlDocument
XmlDocument
XmlDocument doc = new XmlDocument();
XmlElement root = doc.CreateElement("root");
root.SetAttribute("name", "value");
XmlElement child = doc.CreateElement("child");
child.InnerText = "text node";
root.AppendChild(child);
doc.AppendChild(root);
XDocument
XDocument doc = new XDocument(
new XElement("root", new XAttribute("name", "value"),
new XElement("child", "text node"))
);
/*result*/
<root name="value">
<child>text node</child>
</root>
Change InnerText of node in XML
XmlDocument
XmlNode node = _doc.SelectSingleNode("xmlRootNode");
node.InnerText = value;
XDocument
XElement rootNode = _doc.XPathSelectElement("xmlRootNode");
rootNode.Value = "New Value";
XPathSelectElement and XPathSelectElements are extension methods in the System.Xml.XPath namespace.
Save File after edit
Make sure to save the XML after any change.
// Save XmlDocument and XDocument
_doc.Save(filename);
Retrieve Values from XML
XmlDocument
XmlNode node = _doc.SelectSingleNode("xmlRootNode/levelOneChildNode");
string text = node.InnerText;
XDocument
XElement node = _doc.XPathSelectElement("xmlRootNode/levelOneChildNode");
string text = node.Value;
Retrieve the value of each child element whose attribute matches a given value.
XmlDocument
List<string> valueList = new List<string>();
foreach (XmlNode n in nodelist)
{
if(n.Attributes["type"].InnerText == "City")
{
valueList.Add(n.InnerText);
}
}
XDocument
var accounts = _doc.XPathSelectElements("/data/summary/account").Where(c => c.Attribute("type").Value == "setting").Select(c => c.Value);
Append a node
XmlDocument
XmlNode nodeToAppend = _doc.CreateElement("SecondLevelNode");
nodeToAppend.InnerText = "This title is created by code";
/* Append node to parent */
XmlNode firstNode= _doc.SelectSingleNode("xmlRootNode/levelOneChildNode");
firstNode.AppendChild(nodeToAppend);
/*After a change make sure to save the document*/
_doc.Save(fileName);
XDocument
_doc.XPathSelectElement("ServerManagerSettings/TcpSocket").Add(new XElement("SecondLevelNode", "This title is created by code"));
/*After a change make sure to save the document*/
_doc.Save(fileName);