【问题标题】:how to convert xml to string including declaration [duplicate]如何将xml转换为字符串,包括声明[重复]
【发布时间】:2014-06-13 12:41:15
【问题描述】:

我必须将 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>

我也需要这个字符串。 该怎么做?

【问题讨论】:

  • 重复问题的链接位于帖子的顶部。
  • 上面的链接没有帮助。它将字符串转换为 xml,包括声明,但它的声明为 但我想要

标签: c# xml string linq


【解决方案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();

【讨论】:

  • 它可以工作,但是在转换为字符串后,它的显示声明为 但它实际上是 对不起,我不得不取消标记你的答案..
  • 我也在创建它在文档中具有 的 xml 文件..所以我想我必须添加这个 我自己和 doc.ToString() 一起获得所需的输出..
猜你喜欢
  • 2019-11-30
  • 2015-09-25
  • 1970-01-01
  • 2015-01-03
  • 2012-04-13
  • 2021-06-17
  • 2012-10-22
  • 2019-11-28
  • 2019-12-06
相关资源
最近更新 更多