c# - XDocument 文本节点换行

标签 c# xml newline linq-to-xml

我正在尝试使用 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"?>&#10;<NodeName>This is a string&#10;With new lines in it&#10;</NodeName>

关于c# - XDocument 文本节点换行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7485037/

相关文章:

annotations - Stanford NLP Sentiment,句子换行

c - 从标准输出写入文件

c# - 不能在 C# 中使用 stackalloc 来初始化先前声明的指针吗?

c# - 使用 C# 以编程方式输入 cmd.exe 应用程序参数

xml - 我的 xmlstarlet update 命令有什么问题?

xml - Visual Studio 2008 自定义配置 xsd intellisense 自动完成损坏!

xml - 如何删除仅从特定单词的最后一个实例开始的整个字符串?

c# - 分块读取csv文件进行处理

c# - 创建日志文件C#

Python:避免使用打印命令换行