Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I need to convert an XML string into an XmlElement

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> 
like image 583
Dean Avatar asked Sep 13 '10 18:09

Dean


People also ask

What is System XML XmlElement?

XmlAttribute Class (System.Xml)Represents an attribute. Valid and default values for the attribute are defined in a document type definition (DTD) or schema.

What is the difference between XmlNode and XmlElement?

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.

What is XmlDocument?

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).


2 Answers

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.

like image 143
Aliostad Avatar answered Sep 25 '22 17:09

Aliostad


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> 
like image 37
johnrock Avatar answered Sep 25 '22 17:09

johnrock