使用xElement将c#字符串的特殊字符(,&)转换为XML

时间:2023-02-12 21:49:08

C#

c#

noticia.Add(new XElement("Imagem", <BR>));

i need :

我需要:

<Imagem><BR></Imagem>

and not:

而不是:

<Imagem>&lt;BR&gt;</Imagem>

thanks all

感谢所有

2 个解决方案

#1


5  

Just do this

只是这样做

noticia.Add(new XElement("Imagem", new XElement("BR")));

However that will give you an extra / which you NEED or it's not valid XML.

但是,这会给您一个额外的/您需要的/或它不是有效的XML。

<Imagem><BR/></Imagem>

The other options is using CDATA

其他选项是使用CDATA

noticia.Add(new XElement("Imagem", new XCData("<BR>")));

Which will get you

这将让你

<Imagem><![CDATA[<BR>]]></Imagem>

Just generating <Imagem><BR></Imagem> is impossible as it's not valid xml.

仅仅生成
是不可能的,因为它不是有效的xml。

EDIT: If you have the string with other text, in a variable, your only option is CDATA, like this

编辑:如果在变量中有带有其他文本的字符串,那么您唯一的选项就是CDATA,就像这样

var OutClass = "xpto. <BR>";
noticia.Add(new XElement("Imagem", new XCData(OutClass)));

Which results in

这将导致

<Imagem><![CDATA[xpto. <BR>]]></Imagem>

#2


0  

I realy use classes:

我真的用类:

I recive from on class the string:

我在课堂上收到

string OutClass = "xpto. <BR>";

and i use the XElement() in another class.

我在另一个类中使用XElement()。

#1


5  

Just do this

只是这样做

noticia.Add(new XElement("Imagem", new XElement("BR")));

However that will give you an extra / which you NEED or it's not valid XML.

但是,这会给您一个额外的/您需要的/或它不是有效的XML。

<Imagem><BR/></Imagem>

The other options is using CDATA

其他选项是使用CDATA

noticia.Add(new XElement("Imagem", new XCData("<BR>")));

Which will get you

这将让你

<Imagem><![CDATA[<BR>]]></Imagem>

Just generating <Imagem><BR></Imagem> is impossible as it's not valid xml.

仅仅生成
是不可能的,因为它不是有效的xml。

EDIT: If you have the string with other text, in a variable, your only option is CDATA, like this

编辑:如果在变量中有带有其他文本的字符串,那么您唯一的选项就是CDATA,就像这样

var OutClass = "xpto. <BR>";
noticia.Add(new XElement("Imagem", new XCData(OutClass)));

Which results in

这将导致

<Imagem><![CDATA[xpto. <BR>]]></Imagem>

#2


0  

I realy use classes:

我真的用类:

I recive from on class the string:

我在课堂上收到

string OutClass = "xpto. <BR>";

and i use the XElement() in another class.

我在另一个类中使用XElement()。