0

NOTE

Please note, read the comments if you want the missing link to this solution - it's not in the question that this is an "exact duplicate" of.

I'm stumped by the need for a little bit of XML gymnastics. Maybe I'm over complicating this.

I'm trying to add a p element to an XML document. The content of the paragraph may be plain text. Or may have elements within it, i.e link tags, styling, etc.

The code I have currently is below:

foreach (var paragraph in paragraphs)
{
    doc.Add(new XElement("p", 
        new XElement("a", new XAttribute("type", "paranum"), new XText(_paragraphCount)),
        new XText(paragraph.Content)));
}

When I use this, however, any elements that are in there don't come through as elements, but are escaped, probably because they're in XText.

However, I seem to recall trying XElement.Parse, but it not liking it when there is no root element, which makes sense. Sometimes, there aren't even any elements, just text.

How would I go about putting the content of this paragraph in the p element and preserving child elements, if any? Preferably without wrapping it in another element to allow me to do XElement.Parse.

Craig Brett
  • 2,295
  • 1
  • 22
  • 27
  • Why don't you want to wrap it in another element? – dbc Apr 17 '15 at 16:02
  • Well, I'll try the accepted answer for that question, but are you sure it will handle scenarios where there are no inner tags at all, just XText? – Craig Brett Apr 18 '15 at 11:55
  • Yes, the accepted answer works - I checked it. – dbc Apr 18 '15 at 15:26
  • @dbc Just tried this. No dice. The elements collection returns an empty collection. I want both the text and any contained elements. I'd have thought the parsing would've put the text in XText elements or something. – Craig Brett Jun 23 '15 at 14:35
  • Ah, I figured it out. If I use Nodes() rather than Elements() as that answer implies, I get what I'm after. That answer didn't get me the whole way there. I'm not so sure this is a duplicate question as it has a different answer. But hey... – Craig Brett Jun 23 '15 at 21:50
  • Since this is an old question, you could ask the question again, then answer it yourself. – dbc Jun 23 '15 at 22:37
  • Posting another "duplicate" to iron out this little bit of knowledge left out in the answer I'm supposed to have found by seeming magic seems counterproductive. – Craig Brett Oct 25 '16 at 12:32

0 Answers0