LINQ to XML,替换子节点但保留状态[英] LINQ to XML, replace child nodes but keep state

本文是小编为大家收集整理的关于LINQ to XML,替换子节点但保留状态的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我已将以下 XML 作为 IQueryable 传递给方法,即

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> (并且可能添加属性).

我的问题不是实际替换 (XElement.ReplaceWith()),而是替换后的更改并未反映 StringBuilder 使用的 bodySection 变量这一事实.

我将如何让它发挥作用?

推荐答案

你没有真正展示足够的代码 - 特别是,你没有展示你尝试使用的替换代码.

但是,我怀疑主要问题是 bodySection 是一个查询.每次使用它时,它都会再次查询 section - 如果这是从数据库中提取信息,那就这样吧.你可能会发现这就是让它做你想做的所有事情:

var bodySection = articleSection.Descendants("body").ToList();

这样您就可以在内存中获得正文部分,并且在您使用 bodySection 时,您将使用相同的对象集合,而不是再次查询.

本文地址:https://www.itbaoku.cn/post/1557124.html

问题描述

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>

Method:

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

What I want to accomplish is to replace the <pullquote> with a <p> (and maybe add attributes).

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.

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

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.