从xml读取/写入新行字符

时间:2013-02-14 17:41:39

标签: c# xml c#-4.0

我使用xml文件存储一些键/值数据:

<Resource Key="A1" Value="Some text" />

我遇到的问题是,如果它是多行文本,我将如何在Value中保存/加载数据?

<Resource Key="A2" Value="Some text\nin two lines" />

在显示时应该导致

Some text
in two lines

如果我使用

阅读上述资源
XDocument document = XDocument.Load(filePath);

// get all the localized client resource strings
var resource = (from r in document.Descendants("Resource")
                          where r.Attribute("Key").Value == "A2"
                          select r).SingleOrDefault();

它将以双反斜杠读取它:

Some text\\nin two lines.

那么,如何读取/保存新行字符是一些文本,例如,以后可以在WPF应用程序或Web应用程序中显示?

编辑:这是一个示例(正确写入,读取不正确):

<!-- WPF window xaml code -->
<Grid>
  <Button Name="btn" Content="Click me" />
</Grid>

// WPF window code behind
public MainWindow()
{
    InitializeComponent();

    XDocument doc =
          new XDocument(
            new XElement("Resources",
              new XElement("Resource", new XAttribute("Key", "A1"), new XAttribute("Value", @"Some text\nin two lines")))
          );

    const string fileName = @"D:\test.xml";
    doc.Save(fileName);

    doc = XDocument.Load(fileName);

    IDictionary<string, string> keys = (from c in doc.Descendants("Resource")
                                        select c).ToDictionary(c => c.Attribute("Key").Value, c => c.Attribute("Value").Value);

    btn.ToolTip = keys["A1"];
    //btn.ToolTip = "Some text\nin two lines"; // if you uncomment this line, it works as expected
}

1 个答案:

答案 0 :(得分:0)

取消字符串工作

btn.ToolTip = System.Text.RegularExpressions.Regex.Unescape(keys["A1"]);

如果有人知道如何在从xml读取时避免转义(将其读取为非转义状态),我会很高兴听到它。