james raygan
james raygan

Reputation: 701

Convert string to XML using .Net

I store the XML output to String and Again convert this string to XML .I successfully convert XML output to String, but i got problem again converting string to XML.

sample code:

 webservice.Service1 objService1 = new webservice.Service1();
    String s = objService1.HelloWorld();   //Convert XML output into String   
    XmlDocument xd = new XmlDocument();
    xd.LoadXML(s);

I use LoadXML() method, but i got error

Data at the root level is invalid. Line 1 position 1.

Its grateful, if any body give right code to convert String To XML in c#. Thank you,

Upvotes: 1

Views: 61950

Answers (2)

SyntaxError
SyntaxError

Reputation: 1752

You should use XDocument. XDocument is better than XMLDocument. It is very efficient, simple and easy to use.

Your code :

webservice.Service1 objService1 = new webservice.Service1();
    String s = objService1.HelloWorld();   //Convert XML output into String   
    XmlDocument xd = new XmlDocument();
    xd.LoadXml(s);

Solution:

XDocument xd = XDocument.Parse(s);

Upvotes: 7

Chachi
Chachi

Reputation: 164

      XmlDocument xd = new XmlDocument();
      xd.LoadXml("<root>123</root>");

It works. You should print the s value and check it is a valid xml string.

Upvotes: 2

Related Questions