我尝试序列化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>
看起来不错,但验证员并不喜欢它。我整天都在桌子上敲打着头,所以任何示例代码都会非常有用!
由于
答案 0 :(得分:0)
看起来像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。