使用ReplaceWith方法时编码问题的XDocument的XElement [英] Encoding problems with XDocument XElement when using ReplaceWith method
问题描述
我有以下代码:
XDocument doc = XDocument.Load(file);
var x = doc.Descendants("span");
XElement xelm = x.FirstOrDefault(xm => xm.Attribute("class").Value=="screenitems");
Regex rgx = new Regex("^<span class=\"screenitems\">(.*)</span>$");
Match mtc = rgx.Match(xelm.Value);
if (mtc.Success)
{
xelm.ReplaceWith(mtc.Groups[1].Value);
}
doc.Save(file);
当我得到一个匹配和替换的XML文件加载到变量商务部
使用了的XElement
变量 xelm的
,XML文件的内容是越来越编码,因此而不是像一个标记 ReplaceWith
方法< p>
我得到 &放大器; LT; p&放大器; GT
。
When I get a match and replace the content of the XML file loaded into variable doc
using the ReplaceWith
method for the XElement
variable xelm
, the content of the XML file is getting encoded, so instead of having a tag like <p>
I get <p>
.
所以,我怎样才能防止它编码成HTML,但与匹配的正则表达式实际上取代了?
So How can I prevent that it encodes into html but actually replaces with the matched regex expression?
我一些解决方案已经在这里看了看,就像使用 XElement.Parse
方法或 HTTPUtility.HtmlDecode
,但我找不到弄不明白工作。它仍然编码如HTML。
I have looked at some of the solutions here, like using XElement.Parse
method or HTTPUtility.HtmlDecode
, but I couldn't get it to work. It still encodes like html.
推荐答案
虽然你可以尝试和分析你的正则表达式匹配到的XElement
s到解决这个问题,我想你会对此错误的方式。
While you could try and parse your RegEx match into XElement
s to solve the problem, I think you're going about this the wrong way.
据我了解,你的要求是更换跨度
与 screenItems元素
类的内容。而不是做这个使用LINQ到XML和正则表达式的组合,你应该坚持的LINQ to XML。
As I understand it, your requirement is to replace a span
element with the screenItems
class with its contents. Rather than doing this using a combination of LINQ to XML and RegEx, you should stick to LINQ to XML.
找到你所有的跨度
与 screenItems
类元素:
Find all your span
elements with the screenItems
class:
var spans = doc.Descendants("span")
.Where(e => (string)e.Attribute("class") == "screenItems")
.ToList();
然后用自己的内容替换每个这些:
Then replace each of these with their own content:
foreach (var span in spans)
{
span.ReplaceWith(span.Nodes());
}
请参阅的一个工作示例这个小提琴。
这篇关于使用ReplaceWith方法时编码问题的XDocument的XElement的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!