XamlReader.Parse抛出“给定编码中的无效字符”

时间:2011-04-30 12:12:16

标签: .net wpf xaml

我遇到以下代码的问题:

using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
    var content = reader.ReadToEnd();
    ParserContext context = new ParserContext()
    {
        BaseUri = new Uri(Configuration.SkinsFolder)
        //,XmlLang = "utf-8" // I have tried with this parameter and without it
    };
    var result = XamlReader.Parse(content, context);
    return result;
}

相应的xaml,出现问题:

...
<TextBlock>русская надпись</TextBlock>
<TextBlock Text="קח מספר" />
...

在解析这个xaml期间,我得到了异常:

Invalid character in the given encoding. Line 76, position 167.
   at System.Windows.Markup.XamlReaderHelper.RethrowAsParseException(String keyString, Int32 lineNumber, Int32 linePosition, Exception innerException)
   at System.Windows.Markup.XamlReaderHelper.Read(XamlNode& xamlNode)
   at System.Windows.Markup.XamlParser.ReadXaml(Boolean singleRecordMode)
   at System.Windows.Markup.XamlParser._Parse()
   at System.Windows.Markup.XamlParser.Parse()

Xaml文件保存为utf-8

有人知道如何在没有这些问题的情况下加载这个xaml吗? 提前谢谢!

PS:好的,我找到了问题的根源。

加载xaml的正确方法是使用XamlReader.Load方法而不是XamlReader.Parse。在我的情况下,它似乎:

using (Stream stream = new FileStream(source, FileMode.Open))
{
    ParserContext context = new ParserContext()
    {
        BaseUri = new Uri(Configuration.SkinsFolder)
    };
    var result = XamlReader.Load(stream, context);
    return result;
}

感谢所有人!

1 个答案:

答案 0 :(得分:4)

我对德国变音符号有同样的问题。我认为.NET Framework中存在一个错误。尝试使用此函数而不是XamlReader.Parse(内容,上下文):

public static object Parse(string xamlText, ParserContext parserContext)
{
  return System.Windows.Markup.XamlReader.Load((Stream) new MemoryStream(Encoding.UTF8.GetBytes(xamlText)), parserContext);
}