I need to convert an XML string into an XmlElement
Solution 1:
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
.
Solution 2:
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>