Search code examples
c#.netxmllinq-to-xmlxelement

Read data from XElement that has elements mixed with plain content


XElement has the following value:

<parent><child>text inside element</child>and plain content</parent>

How can I convert it to a string that contains: "text inside element and plain content".

What I've tried already?

I tired to use xElement.Value, but this concats the two nodes without putting a space between them: "text inside elementand plain content".


Solution

  • The Text you are looking for is stored in nodes of type XText. So you can get at these nodes like this:

    xElement.DescendantNodes()
            .OfType<XText>()
            .Select(t => t.Value)
    

    That would give you this result:

    text inside element 
    and plain content 
    

    You could then concatenate these as you wish (for example with String.Join).