如何将xml转换为包含声明的字符串

时间:2014-06-13 04:19:22

标签: c# xml string linq

我必须将xml转换为字符串

xml创建为:

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());

我得到字符串:

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

但是跳过声明部分是:

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

我需要字符串

<?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>

我需要在字符串中也有这个。 怎么做?

1 个答案:

答案 0 :(得分:1)

怎么样

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();