构建后将 XDeclaration 添加到 XDocument

发布于 2024-11-17 12:06:10 字数 693 浏览 1 评论 0原文

我有一个 XmlSerializer,用于将对象序列化为 XDocument。

var doc = new XDocument();
using (var writer = doc.CreateWriter())
{
   xmlSerializer.Serialize(writer, object);
}

完成此操作后,我想添加一个 XDeclaration:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>

我按如下所述构建此 XDeclaration:

var decl = new XDeclaration("1.0", "UTF-8", "no");

但是,当我尝试将此 XDeclartion 添加到我的 XDocument 时,我收到以下错误:

System.ArgumentException : Non white space characters cannot be added to content.

我在 Google 上搜索了一段时间,但我已经找到了find 是将 XDeclaration 添加到 XDocument 的构造函数中,在我的情况下(当用 XmlWriter 填充它时)是不可接受的。

I have an XmlSerializer which I use to Serialize an object to an XDocument.

var doc = new XDocument();
using (var writer = doc.CreateWriter())
{
   xmlSerializer.Serialize(writer, object);
}

After this is done, I want to add a XDeclaration:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>

I construct this XDeclaration as described below:

var decl = new XDeclaration("1.0", "UTF-8", "no");

However, when I try to add this XDeclartion to my XDocument, I get the following error:

System.ArgumentException : Non white space characters cannot be added to content.

I searched Google for some time but all I've found is adding the XDeclaration to the constructor of the XDocument which in my case (when filling it with a XmlWriter) is not acceptable.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

顾冷 2024-11-24 12:06:10

使用属性 XDocument.Declaration


编辑

示例代码:

var xmlSerializer = new XmlSerializer(typeof(int));

var doc = new XDocument();

var decl = new XDeclaration("1.0", "utf-8", "no");
doc.Declaration = decl;

using (var writer = doc.CreateWriter())
{
    xmlSerializer.Serialize(writer, 1);
}
doc.Save(File.Create("x.xml"));

此代码产生以下输出:

<?xml version="1.0" encoding="utf-8" standalone="no"?>
<int>1</int>

Use property XDocument.Declaration


EDIT:

Sample code:

var xmlSerializer = new XmlSerializer(typeof(int));

var doc = new XDocument();

var decl = new XDeclaration("1.0", "utf-8", "no");
doc.Declaration = decl;

using (var writer = doc.CreateWriter())
{
    xmlSerializer.Serialize(writer, 1);
}
doc.Save(File.Create("x.xml"));

This code produced following output:

<?xml version="1.0" encoding="utf-8" standalone="no"?>
<int>1</int>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文