使用XMLDocument对象解析在其值中嵌入双引号的xml属性

时间:2014-09-08 20:43:07

标签: c# xml regex

这是一个网络项目。 我从外部源接收部分html字符串。使用XMLDocument解析它的效果很好,除非它遇到带有嵌入式引号的属性,例如下面的“style”属性。

<span id="someId" style="font-family:"Calibri", Sans-Serif;">Some Text</span>

似乎(但我可能错了)LoadXml()认为Calibri之前的双引号结束了style属性,而Calibri是另一个“标记”(标记是我在错误消息中得到的术语)

var xml = new XmlDocument();
xml.LoadXml(<the html string above, properly escaped>); // <--- here is where I get the error message below

"'Calibri' is an unexpected token. Expecting white space. Line 1, position 18."

我可以使用正则表达式替换内部引号,但它会相当丑陋。而且,我最终可能会这样做!

我想也许HtmlAgilityPack会有所帮助,但我找不到好的文档,我宁愿避免使用稀疏文档的第三方库。

有没有办法让LoadXml()接受它(然后,让Attributes集合正确地解析它)?我对此没有多少希望,但无论如何我都把它扔出去了。或者我应该使用除XmlDocument以外的其他类?我愿意使用带有良好文档的第三方库。

1 个答案:

答案 0 :(得分:4)

该数据无效。使用双引号引用的属性不能在属性值中包含双引号。使用单引号引用的属性不能在值中包含单引号。

有效:

<tag attr1="value with 'single' quotes" attr2='value with "double" quotes' />

无效:

<tag attr1="value with "double" quotes" attr2='value with 'single' quotes' />

请注意,无效示例可以按如下方式生效:

<tag attr1="value with &quot;double&quot; quotes" attr2='value with &apos;single&apos; quotes' />
相关问题