I need to convert an XML string into an XmlElement

C#XmlType Conversion

C# Problem Overview


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>

C# Solutions


Solution 1 - C#

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 - C#

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>

Solution 3 - C#

Use XmlDocument.LoadXml:

XmlDocument doc = new XmlDocument();
doc.LoadXml("<item><name>wrench</name></item>");
XmlElement root = doc.DocumentElement;

(Or in case you're talking about XElement, use XDocument.Parse:)

XDocument doc = XDocument.Parse("<item><name>wrench</name></item>");
XElement root = doc.Root;

Solution 4 - C#

You can use XmlDocument.LoadXml() to do this.

Here is a simple examle:

XmlDocument xmlDoc = new XmlDocument(); 
xmlDoc.LoadXml("YOUR XML STRING"); 

Solution 5 - C#

I tried with this snippet, Got the solution.

// Sample string in the XML format
String s = "<Result> No Records found !<Result/>";
// Create the instance of XmlDocument
XmlDocument doc = new XmlDocument();
// Loads the XML from the string
doc.LoadXml(s);
// Returns the XMLElement of the loaded XML String
XmlElement xe = doc.DocumentElement;
// Print the xe
Console.out.println("Result :" + xe);

If any other better/ efficient way to implement the same, please let us know.

Thanks & Cheers

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDeanView Question on Stackoverflow
Solution 1 - C#AliostadView Answer on Stackoverflow
Solution 2 - C#johnrockView Answer on Stackoverflow
Solution 3 - C#dtbView Answer on Stackoverflow
Solution 4 - C#FlorianView Answer on Stackoverflow
Solution 5 - C#Nandagopal TView Answer on Stackoverflow