我有一个XML字符串存储在DB表中,上面有线供稿字符。在我的C#3.5程序中,我使用LINQ将其加载并操作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>
有帮助吗?

解决方案

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

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

这样的事情:

var settings = new XmlWriterSettings() 
    { 
     Indent = true,
     IndentChars = "\n",
     NewLineOnAttributes = true
    }; 

其他提示

感谢您的回答。最后,我可以做到这一点。

我的方法不使用linq2xml/sax parser.am使用StringBuilder生成XML,并在winforms丰富的TextBox Control中显示在UI中。

每当您将XML文档转换为字符串并开始操纵字符串时,您都应该思考:“自我,我做错了什么。”从您的描述中,我不确定这是真的,但是我敢打赌。

如果您要从数据库中提取的XML中的空格很重要,则在将其解析到您的 XElement. 。为此,请使用 XElement.Parse 这样做,例如:

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

当您这样做时,解析器将留下空格字符 XElement 文档的文本节点完全在原始字符串中的位置。 XmlWriter 不会弄乱文本节点中的现有空格(尽管如果您将其告诉缩进,它将添加新的空格),因此这应该为您带来想要的东西。

您可以使用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字符串。

您是否尝试确保文本框处于多行模式,并且 接受马车返回?

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!";
 }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top