开发者

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;
开发者_JS百科

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

Thank you


You need to escape it as &amp;.


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);


Escape it: &amp;.

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


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>"


you can use &amp;


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. :)


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;


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜