简体   繁体   English

使用ReplaceWith方法时XDocument XElement的编码问题

[英]Encoding problems with XDocument XElement when using ReplaceWith method

I have the following code: 我有以下代码:

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);

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 &lt;p&gt . 当我找到一个匹配项并使用XElement变量xelmReplaceWith方法替换加载到变量doc中的XML文件的内容时,该XML文件的内容已得到编码,因此我得到的不是&lt;p&gt <p> &lt;p&gt

So How can I prevent that it encodes into html but actually replaces with the matched regex expression? 那么,如何防止它编码为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. 我在这里查看了一些解决方案,例如使用XElement.Parse方法或HTTPUtility.HtmlDecode ,但是我无法使其正常工作。 It still encodes like html. 它仍然像html一样编码。

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. 虽然您可以尝试将RegEx匹配解析为XElement来解决问题,但我认为您这样做的方式是错误的。

As I understand it, your requirement is to replace a span element with the screenItems class with its contents. 据我了解,您的要求是将span元素替换为带有其内容的screenItems类。 Rather than doing this using a combination of LINQ to XML and RegEx, you should stick to LINQ to XML. 与其将LINQ to XML和RegEx结合使用,不如坚持使用LINQ to XML。

Find all your span elements with the screenItems class: 使用screenItems类查找所有span元素:

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());
}

See this fiddle for a working example. 有关工作示例,请参见此小提琴

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

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