Reputation: 81262
I need to pass the & character inside an XML element, but its not liking it, here is a code sample:
XmlDocument doc = new XmlDocument();
XmlElement batch = doc.CreateElement("Batch");
string item = "<field>http://mylink.com/page.aspx?id=1&disp=2</field>"
batch.InnerXml = item;
Its absolutely crucial I put this link inside, so does anyone know how to get around this?
Thank you
Upvotes: 2
Views: 360
Reputation: 41298
Use .InnerText rather than .InnerXml, and the XmlDocument instance will do all necessary encodings for you, like automatically escaping the & to &
The .InnerXml is used when the string you have is already valid xml which is not to be escaped, which is not the case here.
Upvotes: 2
Reputation: 147240
As others have pointed out, you can just use an &
escape sequence. However, the more elegant approach is not to deal directly with the XML at all.
var doc = new XmlDocument();
var batch = doc.CreateElement("Batch");
var field = doc.CreateElement("field");
field.InnerText = "http://mylink.com/page.aspx?id=1&disp=2"
batch.Children.AppendChild(field);
No need to worry about escaping anything, this way. :)
Upvotes: 3
Reputation: 25687
Escape it as &
. This is called HTML/XML Entities. See more information and list of others entities here and here.
The code should look like this:
string item = "<field>http://mylink.com/page.aspx?id=1&disp=2</field>"
Upvotes: 4
Reputation: 49534
As people are saying, escaping the element will work. However, I find this a little cleaner:
XmlDocument doc = new XmlDocument();
XmlElement batch = doc.CreateElement("Batch");
XmlElement field = doc.CreateElement("field");
string link = "http://mylink.com/page.aspx?id=1&disp=2"
field.InnerText = link;
batch.AppendChild(field);
Upvotes: 8
Reputation: 6825
If you create the element with the Xml methods it will wrap everything up nicely for you. So use the CreateElement
method again and set the InnerText
property of the element to your link.
Upvotes: 2
Reputation: 102458
XmlDocument doc = new XmlDocument();
XmlElement batch = doc.CreateElement("Batch");
string item = "<field>http://mylink.com/page.aspx?id=1&disp=2</field>"
batch.InnerXml = item;
Upvotes: 2
Reputation: 8784
Escape it: &
.
string item = "<field>http://mylink.com/page.aspx?id=1&disp=2</field>";
Upvotes: 6