从/到xml读取/写入换行符

本文关键字:换行符 xml 读取 | 更新日期: 2023-09-27 17:59:05

我使用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
}

从/到xml读取/写入换行符

取消字符串的转换工作

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

如果有人知道如何在从xml读取时避免转义(按照原样读取),我会很高兴听到它。