0

i have to convert an xml into string

The xml is created as:

System.Xml.Linq.XDocument doc = new System.Xml.Linq.XDocument(new System.Xml.Linq.XDeclaration("1.0", "ISO-8859-1",""));
System.Xml.Linq.XElement root = new System.Xml.Linq.XElement("qcs");
System.Xml.Linq.XElement goal_Name = new System.Xml.Linq.XElement("goal", new System.Xml.Linq.XAttribute("name","abc"));
root.Add(goal_Name);
doc.Add(root);
Console.WriteLine(doc.ToString());

I am getting string as:

<qcs>
  <goal name="Goal15">
  </goal>
</qcs>

But skipping declaration part which is:

<?xml version="1.0" encoding="ISO-8859-1"?>

I need string as

<?xml version="1.0" encoding="ISO-8859-1"?>
<qcs>
  <goal name="Goal15">
    <value action="A">0.85</value>
    <value action="B">0.87</value>
  </goal>

I need to have this too in string. How to do that?

Silver
  • 443
  • 2
  • 12
  • 33
  • The link to the duplicate question is at the top of your post. – Tim Jun 13 '14 at 04:35
  • the link above is not helping. it is converting string to xml including declaration but its putting declaration as but i want – Silver Jun 13 '14 at 04:57

1 Answers1

1

How about

XElement root = new XElement("qcs");
XElement goal_Name = new XElement("goal", new System.Xml.Linq.XAttribute("name", "abc"));
root.Add(goal_Name);

XDocument doc = new XDocument(new XDeclaration("1.0", "ISO-8859-1", string.Empty), root);

var wr = new StringWriter();
doc.Save(wr);
Console.Write(wr.GetStringBuilder().ToString());
Console.ReadLine();
Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208
  • it works but after converting to string its showing declaration as but it actually is sorry i had to unmark your answer.. – Silver Jun 13 '14 at 04:54
  • read this http://stackoverflow.com/questions/1543363/why-cant-i-set-the-xdocument-xdeclaration-encoding-type-to-iso-8859-1 – Nikhil Agrawal Jun 13 '14 at 05:11
  • i am also creating the xml file it is having in document..so i think i will had to add this my self along with doc.ToString() to get desired output.. – Silver Jun 13 '14 at 05:19