簡體   English   中英

保留xml中的特殊字符

[英]Preserving special chars in xml

我有一個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解析器。使用StringBuilder生成xml並在winforms Rich文本框控件的UI中顯示它。現在,我可以看到在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 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM