tags:

views:

137

answers:

9

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&amp;disp=2&lt;/field&gt;"
batch.InnerXml = item;

Its absolutely crucial I put this link inside, so does anyone know how to get around this?

Thank you

+10  A: 

You need to escape it as &amp;.

GraemeF
lol - how exactly?
JL
+6  A: 

Escape it: &amp;.

string item = "<field>http://mylink.com/page.aspx?id=1&amp;amp;disp=2&lt;/field&gt;";
Anthony Mills
+2  A: 
XmlDocument doc = new XmlDocument();
XmlElement batch = doc.CreateElement("Batch");
string item = "<field>http://mylink.com/page.aspx?id=1&amp;amp;disp=2&lt;/field&gt;"
batch.InnerXml = item;
Robin Day
+2  A: 

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.

Shawn Steward
+9  A: 

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&amp;disp=2"
field.InnerText = link;
batch.AppendChild(field);
John Gietzen
Yes, much more like it.
JonB
+4  A: 

Escape it as &amp;. 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&amp;amp;disp=2&lt;/field&gt;"
NawaMan
+3  A: 

you can use &amp;

Ismail
+3  A: 

As others have pointed out, you can just use an &amp; 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&amp;disp=2"
batch.Children.AppendChild(field);

No need to worry about escaping anything, this way. :)

Noldorin
+1  A: 

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.

Rob Levine