C# XSL编译转换后输出未知的chr

C# XSL编译转换后输出未知的chr,c#,xml,xslt,C#,Xml,Xslt,我的代码在XSLT输出XML的一开始就输出了一些奇怪的字符,VisualStudio2008和记事本都没有显示出来。但它确实存在,因为VS允许我删除它,然后自动正确格式化XML。我该怎么阻止这一切?这是我的密码: // create the readers for the xml and xsl XmlReader reader = XmlReader.Create( new StringReader(LoadFileAsString(MapPath(xslPat

我的代码在XSLT输出XML的一开始就输出了一些奇怪的字符,VisualStudio2008和记事本都没有显示出来。但它确实存在,因为VS允许我删除它,然后自动正确格式化XML。我该怎么阻止这一切?这是我的密码:

    // create the readers for the xml and xsl
    XmlReader reader = XmlReader.Create(
        new StringReader(LoadFileAsString(MapPath(xslPath)))
    );
    XmlReader input = XmlReader.Create(
        new StringReader(LoadFileAsString(MapPath(xmlPath)))
    );

    // create the xsl transformer
    XslCompiledTransform t = new XslCompiledTransform(true);
    t.Load(reader);

    // create the writer which will output the transformed xml
    StringBuilder sb = new StringBuilder();
    //XmlWriterSettings tt = new XmlWriterSettings();
    //tt.Encoding = Encoding.Unicode;
    XmlWriter results = XmlWriter.Create(new StringWriter(sb));//, tt);

    // write the transformed xml out to a stringbuilder
    t.Transform(input, null, results);

    // return the transformed xml
    WriteStringAsFile(MapPath(outputXmlPath), sb.ToString());


    public static string LoadFileAsString(string fullpathtofile)
    {
        string a = null;
        using (var sr = new StreamReader(fullpathtofile))
            a = sr.ReadToEnd();
        return a;
    }

    public static void WriteStringAsFile(string fullpathtofile, string content)
    {
        File.WriteAllText(fullpathtofile, content.Trim(), Encoding.Unicode);
    }

XML输出文档开头的内容很可能是BOM,它指示Unicode输出中的字节是按大端还是小端顺序排列

此BOM表可能对XML文档的使用者有用;然而,在某些情况下,它可能会导致问题,因此最好不要制造问题

您可以指定是否使用通过
XmlWriterSettings
指定的
编码创建BOM表:

XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
xmlWriterSettings.Encoding = new UTF8Encoding(false);
上面的代码将使用UTF8编码创建文档。除非您的消费系统明确要求UTF16/Unicode编码,或者您正在处理亚洲字符,否则这很可能是您想要的

要创建UTF16/Unicode编码的文档,请使用第二个参数,并将其设置为
false

XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
xmlWriterSettings.Encoding = new UnicodeEncoding(false, false);

谢谢,就是这样。但是,我在File.writealText调用中重置了编码,这是在自讨苦吃,所以我用新的Unicode编码(false,false)替换了encoding.Unicode,它可以工作。有了它,我就能够完全注释掉XmlWriterSettings。