如何将XML转换为字符串,包括声明
本文关键字:字符串 包括 声明 转换 XML | 更新日期: 2023-09-27 18:08:30
我必须把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"?>
我需要string作为
<?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>
我也需要这个字符串。怎么做呢?
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();