I'm looking for the simplest way to convert a string containing valid XML into an XmlElement
object in C#.
How can you turn this into an XmlElement
?
<item><name>wrench</name></item>
XmlAttribute Class (System.Xml)Represents an attribute. Valid and default values for the attribute are defined in a document type definition (DTD) or schema.
XmlElement is just one kind of XmlNode. Others are XmlAttribute, XmlText etc. An Element is part of the formal definition of a well-formed XML document, whereas a node is defined as part of the Document Object Model for processing XML documents.
The XmlDocument class is an in-memory representation of an XML document. It implements the W3C XML Document Object Model (DOM) Level 1 Core and the Core DOM Level 2. DOM stands for document object model. To read more about it, see XML Document Object Model (DOM).
Use this:
private static XmlElement GetElement(string xml) { XmlDocument doc = new XmlDocument(); doc.LoadXml(xml); return doc.DocumentElement; }
Beware!! If you need to add this element to another document first you need to Import it using ImportNode
.
Suppose you already had a XmlDocument with children nodes, And you need add more child element from string.
XmlDocument xmlDoc = new XmlDocument(); // Add some child nodes manipulation in earlier // .. // Add more child nodes to existing XmlDocument from xml string string strXml = @"<item><name>wrench</name></item> <item><name>screwdriver</name></item>"; XmlDocumentFragment xmlDocFragment = xmlDoc.CreateDocumentFragment(); xmlDocFragment.InnerXml = strXml; xmlDoc.SelectSingleNode("root").AppendChild(xmlDocFragment);
The Result:
<root> <item><name>this is earlier manipulation</name> <item><name>wrench</name></item> <item><name>screwdriver</name> </root>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With