6

我在 db 表中存储了一个带有换行符的 xml 字符串。在我的 C# 3.5 程序中,我使用 Linq to xml 加载和操作它,然后在 UI 表单的文本框控件中将其显示为字符串。

我需要缩进这个 xml 并在 UI 中显示它时保留换行符/回车符。

能够缩进它,但我如何在 xml 中保留 LF/CR 字符?

这是示例 C# 代码:

    XElement rootNode = CreateRootNode();
    XElement testXmlNode = XElement.Parse(xmlFromDbWithLFChars);

    rootNode.Add(testXmlNode );

    var builder = new StringBuilder();
    var settings = new XmlWriterSettings()
    {
     Indent = true
    };

    using (var writer = XmlWriter.Create(builder, settings))
    {
     rootNode.WriteTo(writer);
    }
    xmlString  = builder.ToString();   

    xmlString = xmlString.Replace("
", Environment.NewLine); //Doesnt work

    xmlString = xmlString.Replace("
", Environment.NewLine);  //Doesnt work

//Heres how the xml should look like in the UI control:
 <TestNode
             name="xyz"
             Id="12">
             <Children>
                  <Child name="abc" location="p" />
             </Children>
    </TestNode>
4

5 回答 5

3

您要做的是在 XmlWriter 上设置格式设置,因此更改您的行:

var settings = new XmlWriterSettings() 
    { 
     Indent = true 
    }; 

对于这样的事情:

var settings = new XmlWriterSettings() 
    { 
     Indent = true,
     IndentChars = "\n",
     NewLineOnAttributes = true
    }; 
于 2010-11-16T15:20:16.830 回答
1

谢谢大家的回复。最后,我可以得到这个工作。

我的方法不使用 Linq2Xml/SAX 解析器。我使用 StringBuilder 生成 xml 并在 winforms 富文本框控件的 UI 中显示它。现在,我可以在 UI 中看到换行符。

于 2010-11-17T08:01:33.777 回答
0

每当您将 XML 文档转换为字符串并开始操作该字符串时,您应该对自己说:“我自己,我做错了什么。” 我不确定你的描述是否属实,但我敢打赌。

如果您从数据库中提取的 XML 中的空白很重要,您希望在将其解析为XElement. 为此,请使用执行此操作的重载XElement.Parse,例如:

XElement testXmlNode = XElement.Parse(xmlFromDbWithLFChars, LoadOptions.PreserveWhitespace);

执行此操作时,解析器将在已解析文档的文本节点中留下空白字符,与XElement它们在原始字符串中的位置完全相同。 XmlWriter不会与文本节点中的现有空格混淆(尽管如果你告诉它缩进它会添加新的空格),所以这应该可以得到你想要的。

于 2010-11-12T05:45:22.700 回答
0

您可以使用 XmlReader 来保留新行和所有内容。这是在测试时对我有用的示例代码:

System.Xml.XmlReader reader = System.Xml.XmlReader.Create("XML URI here");
System.Text.StringBuilder sb = new System.Text.StringBuilder();
while (reader.Read())
{
    sb.Append(reader.ReadOuterXml());
}
reader.Close();
txtXML.InnerText = sb.ToString();
txtXML.Visible = true;

在我加载 XML 文件的测试中,您可以加载您操作的 XML 字符串。

于 2010-11-14T08:12:27.317 回答
0

您是否尝试过确保文本框处于多行模式并接受回车

public void CreateMyMultilineTextBox() {
   // Create an instance of a TextBox control.
   TextBox textBox1 = new TextBox();

   // Set the Multiline property to true.
   textBox1.Multiline = true;
   // Add vertical scroll bars to the TextBox control.
   textBox1.ScrollBars = ScrollBars.Vertical;
   // Allow the RETURN key to be entered in the TextBox control.
   textBox1.AcceptsReturn = true;
   // Allow the TAB key to be entered in the TextBox control.
   textBox1.AcceptsTab = true;
   // Set WordWrap to true to allow text to wrap to the next line.
   textBox1.WordWrap = true;
   // Set the default text of the control.
   textBox1.Text = "Welcome!";
 }
于 2010-11-19T15:50:37.230 回答