Reputation: 1350
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 > 3</root>"
.
EDIT: I did not express myself clear. Is there a way automatically convert special for XML
characters?
Upvotes: 0
Views: 1417
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 > 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
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
Reputation: 15613
string value="Operation 2 > 3";
string xmlValue= "<root>"+ value.Replace("<","<").Replace("&", "&")
.Replace(">", ">")
.Replace("\"", """)
.Replace("'", "'") + "</root>"
Upvotes: 3