如果以某种方式声明 XmlTextWriter,则会出现命名空间重新定义异常
我正在构建一个 XDocument 并使用以下代码将其序列化为 UTF8 字符串:
string xmlString = "";
using (MemoryStream ms = new MemoryStream())
{
using (XmlWriter xw = new XmlTextWriter(ms, Encoding.UTF8))
{
doc.Save(xw);
xw.Flush();
StreamReader sr = new StreamReader(ms);
ms.Seek(0, SeekOrigin.Begin);
xmlString = sr.ReadToEnd();
}
}
这工作得很好。
然后我需要切换声明符是否序列化为字符串。我将代码更改为:
string xmlString = "";
using (MemoryStream ms = new MemoryStream())
{
XmlWriterSettings settings = new XmlWriterSettings()
{
OmitXmlDeclaration = !root.IncludeDeclarator,
Encoding = Encoding.UTF8
};
using (XmlWriter xw = XmlTextWriter.Create(ms, settings))
{
doc.Save(xw);
xw.Flush();
StreamReader sr = new StreamReader(ms);
ms.Seek(0, SeekOrigin.Begin);
xmlString = sr.ReadToEnd();
}
}
这会在 doc.Save(xw) 上引发以下异常:
前缀 '' 无法重新定义 '' 到同一内的 'my_schema_here' 开始元素标记。
我试图弄清楚为什么如果作者是“new”的,则可以保存XDoc,但如果是“.Create”的,则不能保存。有什么想法吗?
乔丹
I am bulding up an XDocument and serializing it to a UTF8 string with the following code:
string xmlString = "";
using (MemoryStream ms = new MemoryStream())
{
using (XmlWriter xw = new XmlTextWriter(ms, Encoding.UTF8))
{
doc.Save(xw);
xw.Flush();
StreamReader sr = new StreamReader(ms);
ms.Seek(0, SeekOrigin.Begin);
xmlString = sr.ReadToEnd();
}
}
This worked fine.
I then needed to toggle whether or not the declarator was serialized to the string. I changed the code to this:
string xmlString = "";
using (MemoryStream ms = new MemoryStream())
{
XmlWriterSettings settings = new XmlWriterSettings()
{
OmitXmlDeclaration = !root.IncludeDeclarator,
Encoding = Encoding.UTF8
};
using (XmlWriter xw = XmlTextWriter.Create(ms, settings))
{
doc.Save(xw);
xw.Flush();
StreamReader sr = new StreamReader(ms);
ms.Seek(0, SeekOrigin.Begin);
xmlString = sr.ReadToEnd();
}
}
This throws the following exception on doc.Save(xw):
The prefix '' cannot be redefined from
'' to 'my_schema_here' within the same
start element tag.
I am trying to figure out why the XDoc can be saved if the writer is "new"ed up, but not if it is ".Create"d. Any ideas?
Jordon
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我通过将命名空间添加到 XDocument 中根元素的名称来修复此问题。不过,奇怪的是,如果使用“new XmlTextWriter()”而不是“XmlTextWriter.Create()”或“XmlWriter.Create()”,则不需要这样做。
乔丹
I fixed this by adding the namespace to the name of the root element in the XDocument. Still, it's strange that this isn't necessary if "new XmlTextWriter()" is used instead of "XmlTextWriter.Create()" or "XmlWriter.Create()".
Jordon