我正在尝试使用以下命令将换行符插入文本节点XText
来自 Linq XML 命名空间。
我有一个包含换行符的字符串,但是我需要弄清楚如何将它们转换为实体字符(即
) 而不是仅仅让它们作为新行出现在 XML 中。
XElement element = new XElement( "NodeName" );
...
string example = "This is a string\nWith new lines in it\n";
element.Add( new XText( example ) );
The XElement
然后使用写出XmlTextWriter
这会导致文件包含换行符而不是实体替换。
有没有人遇到过这个问题并找到解决方案?
EDIT:
当我将 XML 加载到 EXCEL 中时,问题就显现出来了,EXCEL 似乎不喜欢换行符,但接受实体替换。结果是换行符不会显示在 EXCEL 中,除非我将其替换为
Nick.
作弊:
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.CheckCharacters = false;
settings.NewLineChars = " ";
XmlWriter writer = XmlWriter.Create(..., settings);
element.WriteTo(writer);
writer.Flush();
UPDATE:
完整的程序
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();
}
}
}
OUTPUT:
C:\Users\...\\ConsoleApplication1\bin\Release>ConsoleApplication1.exe
<?xml version="1.0" encoding="ibm850"?> <NodeName>This is a string With new lines in it </NodeName>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)