XDocument文本节点换行 [英] XDocument Text Node New Line
问题描述
我正在尝试使用Linq XML名称空间中的XText
将换行符插入文本节点.
I'm trying to get a newline into a text node using XText
from the Linq XML namespace.
我有一个包含换行符的字符串,但是我需要弄清楚如何将它们转换为实体字符(即
),而不仅仅是让它们以XML的形式出现在换行符中.
I have a string which contains newline characters however I need to work out how to convert these to entity characters (i.e.
) rather than just having them appear in the XML as new lines.
XElement element = new XElement( "NodeName" );
...
string example = "This is a string\nWith new lines in it\n";
element.Add( new XText( example ) );
然后使用XmlTextWriter
写出XElement
,这将导致文件包含换行符而不是实体替换.
The XElement
is then written out using an XmlTextWriter
which results in the file containing the newline rather than an entity replacement.
有没有人遇到这个问题并找到解决方案?
Has anyone come across this problem and found a solution?
当我将XML加载到EXCEL中时,问题就显现出来了,该EXCEL似乎不喜欢换行符,但是它接受实体替换.结果是除非我用
The problem manifests itself when I load the XML into EXCEL which doesn't seem to like the newline character but which accepts the entity replacement. The result is that newlines aren't showing in EXCEL unless I replace them with
尼克.
推荐答案
作弊:
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>
这篇关于XDocument文本节点换行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!