[已解决]保留“\ n” XmlNode.InnerText中的字符 [英] [Solved] Retaining "\n" character in XmlNode.InnerText

查看:166
本文介绍了[已解决]保留“\ n” XmlNode.InnerText中的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个winform应用程序,允许用户操作xml文件。 xml文件包含描述节点,我在多行文本框中显示该节点。然后用户可以通过添加回车等来编辑描述。



当我使用文本框中的值重置描述node.InnerText时,它不会保留\ n字符。当我打开xml文件时,我需要innerText的值来包含实际的字符\ n,即

这是第一行\ n这是第二行\ n



当我调试代码并查看textbox.Text的值时,我可以在视觉上看到\ n字符但在设置节点之后。 InnerText = textbox.text,\ n不可见,在xml文件中也不可见。



我试过node.InnerText.Replace( Enviornment.NewLine,\ n)在我设置了InnerXml但它没有效果。



还有其他任何想法吗?

谢谢!



更新:

由OP自己解决 - 张贴为答案之一。

I have a winform app that allows the user to manipulate a xml file. The xml file contains a description node and I display that node in a multiline text box. The user can then edit the description by adding carriage returns etc.

When I go to reset the description node.InnerText with the value from the textbox, it does not retain the "\n" character. When I open the xml file, I need the value of the innerText to contain the actual character "\n" i.e.
This is the first line\nThis is the second line\n

When I am debugging the code and I look at the value of the textbox.Text, I can visually see the "\n" characters but after I set the node.InnerText = textbox.text, the "\n" are not visible and are not visible in the xml file either.

I have tried node.InnerText.Replace(Enviornment.NewLine,"\n") after I set the InnerXml but it has no effect.

Any other ideas?
thanks!

UPDATE:
Solved by OP himself - posted as one of the answers.

推荐答案

对不起,我是傻瓜...当我设置node.InnerText时我最终做了:

node.InnerText = value.Replace(Envirnment.Newline,\\\ \\ n;



我忘了逃避\ n,一旦我添加了\\ n,然后在xml中显示了\ n字符。



无论如何谢谢!
Sorry, I was stupid... When I set the node.InnerText I ended up doing :
node.InnerText = value.Replace(Envirnment.Newline, "\\n";

I forgot to escape the \n, once I added the \\n, then the \n character showed up in the xml.

Thanks anyway!


我无法使用以下测试代码重现您的问题:



I could not reproduce your problem with the following test code:

static void Main(string[] args)
{
  XmlDocument doc = new XmlDocument();
  XmlNode node = doc.CreateNode(XmlNodeType.Element, "Test", "");
  node.InnerText = "hello\nworld";
  doc.AppendChild(node);
  Console.WriteLine(doc.InnerXml);
}


将文本包装在CDATA节点中应该可以解决问题。当从XML文件中读回数据时,这将保留回车。



干杯!
Wrapping the text in a CDATA node should do the trick. That will preserve the carriage returns when the data is read back from the XML file.

Cheers!


这篇关于[已解决]保留“\ n” XmlNode.InnerText中的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆