new2ios
new2ios

Reputation: 1350

How to convert string to a valid XML (with conversion) in C#?

How to convert simple string to a valid XML within <root> element using C#?

So if I have string "Operation 2 > 3" I need to convert it to "<root>Operation 2 &gt; 3</root>".

EDIT: I did not express myself clear. Is there a way automatically convert special for XML characters?

Upvotes: 0

Views: 1417

Answers (3)

H. de Jonge
H. de Jonge

Reputation: 890

By doing this (using System.Xml.Linq)

XElement el = new XElement("root");
el.Add(new XText("Operation 2 > 3"));
string sXML = el.ToString();    // Result: <root>Operation 2 &gt; 3</root>

you just create a root node in memory and fill it with the content you want. The XElement class will take care of all the 'escaping' needed to make this valid XML text.

Upvotes: 1

Chakravarty A
Chakravarty A

Reputation: 84

Try this:

using System.Xml;

string s = "hello";
XmlDocument xml = new XmlDocument();
xml.LoadXml(string.Format("<root>{0}</root>", s));

You can edit the variable s with your text.

Upvotes: 1

Ghasem
Ghasem

Reputation: 15613

string value="Operation 2 > 3";
string xmlValue= "<root>"+ value.Replace("<","&lt;").Replace("&", "&amp;")
                                                   .Replace(">", "&gt;")
                                                   .Replace("\"", "&quot;")
                                                   .Replace("'", "&apos;") + "</root>"

Upvotes: 3

Related Questions