简体   繁体   English

XML和&字符

[英]XML and the & character

I need to pass the & character inside an XML element, but its not liking it, here is a code sample: 我需要在XML元素中传递&字符,但它不喜欢它,这里是一个代码示例:

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

You need to escape it as &amp; 你需要逃避它和&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; 逃避它: &amp; .

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

Escape it as &amp; 逃避它&amp; . This is called HTML/XML Entities. 这称为HTML / XML实体。 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>"

你可以用&amp;

As others have pointed out, you can just use an &amp; 正如其他人所指出的,你可以使用&amp; escape sequence. 逃脱序列。 However, the more elegant approach is not to deal directly with the XML at all. 但是,更优雅的方法是根本不直接处理XML。

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. 如果使用Xml方法创建元素,它将很好地为您包装所有内容。 So use the CreateElement method again and set the InnerText property of the element to your link. 因此,再次使用CreateElement方法并将元素的InnerText属性设置为链接。

Use .InnerText rather than .InnerXml, and the XmlDocument instance will do all necessary encodings for you, like automatically escaping the & to & 使用.InnerText而不是.InnerXml,XmlDocument实例将为您执行所有必要的编码,例如自动转义&到&

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. 当您拥有的字符串已经是有效的xml且不被转义时使用.InnerXml,这不是这里的情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM