我正在尝试使用 Linq XML 命名空间中的 XText
将换行符添加到文本节点中。
我有一个包含换行符的字符串,但是我需要弄清楚如何将它们转换为实体字符(即
),而不是让它们作为新行出现在 XML 中.
XElement element = new XElement( "NodeName" );
...
string example = "This is a string\nWith new lines in it\n";
element.Add( new XText( example ) );
XElement
然后使用 XmlTextWriter
写出,这导致文件包含换行符而不是实体替换。
有没有人遇到过这个问题并找到了解决方案?
编辑:
当我将 XML 加载到 EXCEL 中时,问题就出现了,EXCEL 似乎不喜欢换行符,但接受实体替换。结果是换行符不会显示在 EXCEL 中,除非我将它们替换为
尼克。
最佳答案
作弊:
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.CheckCharacters = false;
settings.NewLineChars = " ";
XmlWriter writer = XmlWriter.Create(..., settings);
element.WriteTo(writer);
writer.Flush();
更新:
完整的程序
using System;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
XElement element = new XElement( "NodeName" );
string example = "This is a string\nWith new lines in it\n";
element.Add( new XText( example ) );
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.CheckCharacters = false;
settings.NewLineChars = " ";
XmlWriter writer = XmlWriter.Create(Console.Out, settings);
element.WriteTo(writer);
writer.Flush();
}
}
}
输出:
C:\Users\...\\ConsoleApplication1\bin\Release>ConsoleApplication1.exe
<?xml version="1.0" encoding="ibm850"?> <NodeName>This is a string With new lines in it </NodeName>
关于c# - XDocument 文本节点换行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7485037/