tags:

views:

227

answers:

2

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?

A: 

It will be better to use Xml Tramsformation, look here for how to do it, and here for xsl syntax

ArsenMkrt
XML Transformation using XSL is not really an option here, it would go against everything that has already been done.
BK
The only way that I see this working, is to convert the entire collection toList() and to work with it from there
BK
+1  A: 

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.

Jon Skeet
You are correct, working with the entire collection List<XElement> seems to be the only solution
BK
@BK: Strictly speaking, it doesn't have to be a `List<XElement>` - anything which materializes the query and maintains the results will do. The actual storage is an implementation detail - but a list is the simplest approach.
Jon Skeet