[英]XmlDocument throwing “An error occurred while parsing EntityName”
I have a function where I am passing a string as params called filterXML which contains '&' in one of the properties. 我有一个函数,我传递一个字符串作为params称为filterXML,其中包含一个属性中的'&'。
I know that XML will not recognize it and it will throw me an err. 我知道XML不会识别它,它会让我犯错误。 Here is my code:
这是我的代码:
public XmlDocument TestXMLDoc(string filterXml)
{
XmlDocument doc = new XmlDocument();
XmlNode root = doc.CreateElement("ResponseItems");
// put that root into our document (which is an empty placeholder now)
doc.AppendChild(root);
try
{
XmlDocument docFilter = new XmlDocument();
docFilter.PreserveWhitespace = true;
if (string.IsNullOrEmpty(filterXml) == false)
docFilter.LoadXml(filterXml); //ERROR THROWN HERE!!!
What should I change in my code to edit or parse filterXml? 我应该在代码中更改哪些内容来编辑或解析filterXml? My filterXml looks like this:
我的filterXml看起来像这样:
<Testing>
<Test>CITY & COUNTY</Test>
</Testing>
I am changing my string value from & to &. 我正在将&#的字符串值更改为。 Here is my code for that:
这是我的代码:
string editXml = filterXml;
if (editXml.Contains("&"))
{
editXml.Replace('&', '&');
}
But its giving me an err on inside the if statement : Too many literals. 但它在if语句中给我一个错误:太多的文字。
The file shown above is not well-formed XML because the ampersand is not escaped. 上面显示的文件不是格式良好的XML,因为&符号未被转义。
You can try with: 您可以尝试:
<Testing>
<Test>CITY & COUNTY</Test>
</Testing>
or: 要么:
<Testing>
<Test><![CDATA[CITY & COUNTY]]></Test>
</Testing>
About the second question: there are two signatures for String.Replace. 关于第二个问题:String.Replace有两个签名。 One that takes characters, the other that takes strings.
一个取字符,另一个取字符串。 Using single quotes attempts to build character literals - but "&", for C#, is really a string (it has five characters).
使用单引号尝试构建字符文字 - 但对于C#而言,“&amp;”实际上是一个字符串(它有五个字符)。
Does it work with double quotes? 它是否适用于双引号?
editXml.Replace("&", "&");
If you would like to be a bit more conservative, you could also write code to ensure that the &s you are replacing are not followed by one of 如果你想保守一点,你也可以编写代码来确保你所替换的&s之后没有其中一个
amp; quot; apos; gt; lt; or #
(but this would still not be a perfect filtering) (但这仍然不是一个完美的过滤)
To specify an ampersand in XML you should use &
要在XML中指定&符,您应该使用
&
since the ampersand sign ('&') has a special meaning in XML. 因为&符号('&')在XML中具有特殊含义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.