问题描述
我将以下XML作为IQueryable传递给方法,即
I've got the following XML passed as an IQueryable to a method, i.e.
XML:
<body>
<p>Some Text</p>
<p>Some Text</p>
<pullquote>This is pullquote</pullquote>
<p>Some Text</p>
<p>Some Text</p>
<body>
方法:
public static string CreateSection(IQueryable<XElement> section)
{
var bodySection = from b in articleSection.Descendants("body")
select b;
//Do replacement here.
var bodyElements = bodySection.Descendants();
StringBuilder paragraphBuilder = new StringBuilder();
foreach (XElement paragraph in bodyElements)
{
paragraphBuilder.Append(paragraph.ToString());
}
return paragraphBuilder.ToString();
}
我要完成的是用<p>
替换<pullquote>
(也许添加属性).
What I want to accomplish is to replace the <pullquote>
with a <p>
(and maybe add attributes).
我的问题不是实际的替换(XElement.ReplaceWith()),而是替换后的更改未反映StringBuilder使用的bodySection变量的事实.
My problem is not the actual replacement (XElement.ReplaceWith()) but the fact that after the replacement the changes does not reflect the bodySection variable that gets used by the StringBuilder.
我将如何使其正常工作?
How would I go about getting this to work?
推荐答案
您没有真正显示足够的代码-特别是,您还没有显示要尝试使用的替换代码
You haven't really shown enough code - in particular, you haven't shown the replacement code you're trying to use.
但是,我怀疑主要问题是bodySection
是一个查询.每次使用它时,它都会再次查询section
-如果这是从数据库中提取信息,就这样吧.您可能会发现,这是使它按您想要的方式工作的全部条件:
However, I suspect the main problem is that bodySection
is a query. Every time you use it, it will query section
again - and if that's pulling information from the database, then so be it. You may find that this is all that's required to make it do what you want:
var bodySection = articleSection.Descendants("body").ToList();
这样,您便可以将正文部分存储在内存中,并且每次使用bodySection
时,都将使用相同的对象集合,而不是再次查询.
That way you've then got the body sections in memory, and any time you use bodySection
you'll be using the same collection of objects, rather than querying again.
这篇关于LINQ to XML,替换子节点但保持状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!