我有一个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.
我在谷歌搜索了一段时间,但我发现只是将XDeclaration添加到XDocument的构造函数中,在我的情况下(当用XmlWriter填充它时)是不可接受的。
答案 0 :(得分:6)
修改强>:
示例代码:
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>