Skip to main content
 首页 » 编程设计

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

2024年02月06日11虾米姐

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

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

似乎(但我可能错了)LoadXml() 认为 Calibri 之前的双引号结束了样式属性并且 Calibri 是另一个“ token ”( token 是我在错误消息中得到的术语) .

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

我可以使用 Regex 来替换内部引号,但它会很丑陋。而且,我很可能最终会这样做!

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

有没有办法让 LoadXml() 接受它(并随后让 Attributes 集合正确解析它)?我对此不抱太大希望,但无论如何我都会把它扔出去。或者我应该使用 XmlDocument 以外的另一个类吗?我愿意使用具有良好文档的第 3 方库。

请您参考如下方法:

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

有效:

<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' />