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