【问题标题】:Serialize XML to File causing malformations?将 XML 序列化为文件导致畸形?
【发布时间】:2013-03-01 23:09:29
【问题描述】:

我正在尝试序列化 XML 并创建一个文件。我正在从使用 xsd.exe 从 XSD 自动生成的对象进行序列化。该文件处理并创建得很好。但是每当我针对验证工具运行它时,我都会收到一个错误 Prolog 中不允许的内容

我的猜测是在 xml 声明之前有一些格式错误的字符,但我看不到它们,也看不到那里的任何字节。这是我序列化和创建 XML 文档的代码:

XmlSerializer ser = new XmlSerializer(typeof(ContinuityOfCareRecord));
            XmlWriterSettings settings = new XmlWriterSettings()
            {
                Encoding = Encoding.UTF8,
                ConformanceLevel = ConformanceLevel.Document,
                OmitXmlDeclaration = false,
                Indent = true,
                NewLineChars = "\n",
                CloseOutput = true,
                NewLineHandling = NewLineHandling.Replace,
                CheckCharacters = true
            };
using (XmlWriter myWriter = XmlWriter.Create(ms, settings))
            {
                myWriter.Flush();
                //myWriter.WriteProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"ccr.xsl\"");
                ser.Serialize(myWriter, myCCR);
            }

看起来很简单,但是如果输出 XML 文件的开头有格式错误的字符,我该如何删除这些字符?

XML 文档开始如下:

<?xml version="1.0" encoding="utf-8"?> <ContinuityOfCareRecord xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="urn:astm-org:CCR"> <CCRDocumentObjectID>testccr</CCRDocumentObjectID> <Language>

看起来正确,但验证器不喜欢它。我整天都在敲桌子,所以任何示例代码都会非常有帮助!

谢谢

【问题讨论】:

  • 您使用的是什么验证工具?您能否将 XML 反序列化回 C# 中的对象而不会出错?

标签: c# xml serialization xml-serialization


【解决方案1】:

看起来像一个 BOM 字符的问题,以这种方式编写代码会有所帮助:

using (XmlTextWriter myWriter = new XmlTextWriter(ms, new System.Text.UTF8Encoding(false)))
        {
            myWriter.Flush();
            //myWriter.WriteProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"ccr.xsl\"");
            ser.Serialize(myWriter, myCCR);
        }

这将删除 BOM 字符,文件将以 UTF-8 编码,不带 BOM。

【讨论】:

  • 我错过了什么吗?我以为你不能创建 XMLWriter 的实例。我实际上在那条线上遇到了一个错误..
猜你喜欢
  • 1970-01-01
  • 2018-11-20
  • 1970-01-01
  • 2021-02-16
  • 2022-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多