使用LINQ To XML读取多行文本属性时保留换行符
用LINQ To XML读取XML文件时保留多行文本属性中的换行符
在使用System.Xml.Linq读取XML文件时,属性中包含的多行文本换行符会被默认替换为空格,需要通过调整读取配置来保留原始换行符。
示例XML文件
<?xml version="1.0" encoding="utf-8"?> <TestRoot> <Properties Description="Line 1 Line 2" /> </TestRoot>
尝试的代码
const string xmlPath = @"C:\Blah\Test.xml"; var rootElement = XElement.Load(xmlPath); var propertiesElement = rootElement.Element("Properties")!; var descriptionAttribute = propertiesElement.Attribute("Description")!; string description = descriptionAttribute.Value; Console.WriteLine(description);
输出对比
预期输出
Line 1 Line 2
实际输出
Line 1 Line 2
解决方案
默认的XElement.Load()会遵循XML规范对属性值做规范化处理,将换行符替换为空格。要保留原始换行符,需通过XmlReader配合XmlReaderSettings关闭规范化功能:
const string xmlPath = @"C:\Blah\Test.xml"; var settings = new XmlReaderSettings { Normalization = false // 关闭属性值规范化,保留原始换行符 }; using (var reader = XmlReader.Create(xmlPath, settings)) { var rootElement = XElement.Load(reader); var propertiesElement = rootElement.Element("Properties")!; var descriptionAttribute = propertiesElement.Attribute("Description")!; string description = descriptionAttribute.Value; Console.WriteLine(description); }
执行上述代码后,即可得到保留换行符的预期输出。
内容的提问来源于stack exchange,提问作者SimonOR
相关产品推荐
相关产品推荐

