JL.
JL.

Reputation: 81262

XML and the & character

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

Answers (9)

Rob Levine
Rob Levine

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

Noldorin
Noldorin

Reputation: 147240

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&disp=2"
batch.Children.AppendChild(field);

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

Upvotes: 3

IsmailS
IsmailS

Reputation: 10863

you can use &amp;

Upvotes: 3

NawaMan
NawaMan

Reputation: 25687

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;disp=2</field>"

Upvotes: 4

John Gietzen
John Gietzen

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

Shawn Steward
Shawn Steward

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

Robin Day
Robin Day

Reputation: 102458

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

Upvotes: 2

Anthony Mills
Anthony Mills

Reputation: 8784

Escape it: &amp;.

string item = "<field>http://mylink.com/page.aspx?id=1&amp;disp=2</field>";

Upvotes: 6

GraemeF
GraemeF

Reputation: 11457

You need to escape it as &amp;.

Upvotes: 10

Related Questions