Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert xmlstring into XmlNode

Tags:

c#

.net

xml

i have one xml string like this

string stxml="<Status>Success</Status>";

I also creaated one xml document

  XmlDocument doc = new XmlDocument();
  XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
  doc.AppendChild(docNode);
  XmlNode rootNode = doc.CreateElement("StatusList");
  doc.AppendChild(rootNode);

i need an output like this.

  <StatusList>
  <Status>Success</Status>
  </StatusList>

How can i achieve this.if we using innerhtml,it will insert.But i want to insert xml string as a xmlnode itself

like image 751
user922834 Avatar asked Apr 10 '12 05:04

user922834


2 Answers

A very simple way to achieve what you are after is to use the often overlooked XmlDocumentFragment class:

  XmlDocument doc = new XmlDocument();
  XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
  doc.AppendChild(docNode);
  XmlNode rootNode = doc.CreateElement("StatusList");
  doc.AppendChild(rootNode);

  //Create a document fragment and load the xml into it
  XmlDocumentFragment fragment = doc.CreateDocumentFragment();
  fragment.InnerXml = stxml;
  rootNode.AppendChild(fragment);
like image 169
dash Avatar answered Oct 22 '22 00:10

dash


Using Linq to XML:

string stxml = "<Status>Success</Status>";
XDocument doc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"),
             new XElement("StatusList", XElement.Parse(stxml)));
like image 1
ionden Avatar answered Oct 22 '22 00:10

ionden