1

I have this xml:

    <root>      
      <sub>maintext1
        <subsub>subtext1</subsub>
        <subsub>subtext2</subsub>
      </sub>          
    </root>

I initially tried < sub>.Value, but this returned everything inside the sub, then < sub>.ToString which does the same thing. I searched for a solution but everywhere was used the xmlElement.InnerText but I need it for xElement which isn't available. How can I use the inner text property for the xElement?

Cobold
  • 2,563
  • 6
  • 34
  • 51
  • 1
    @sll and lazyberezovsky , Why is this xml invalid and why can't I have `maintext1 between node and element.`? It seems to be a completely valid xml. I may be wrong. A reference please. – L.B Nov 28 '12 at 21:08
  • 1
    Agreed, this XML is valid and it parses fine. – vcsjones Nov 28 '12 at 21:09
  • possible duplicate of [Best way to get InnerXml of an XElement?](http://stackoverflow.com/questions/3793/best-way-to-get-innerxml-of-an-xelement) – Sergey Berezovskiy Nov 28 '12 at 21:18
  • Apologize for confisuing I was wrong – sll Nov 29 '12 at 10:58

2 Answers2

1

maintext1 creates a text node, so you could do something like this:

var xml = @"<root>      
<sub>maintext1
<subsub>subtext1</subsub>
<subsub>subtext2</subsub>
</sub>          
</root>";
var doc = XDocument.Parse(xml);
var txt = (IEnumerable<object>)doc.XPathEvaluate("/root/sub/text()");
var textNode = (XText)txt.First();
Console.WriteLine(textNode.Value);

Note that you will need the following namespaces imported for this to compile:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.Xml.XPath;
vcsjones
  • 138,677
  • 31
  • 291
  • 286
1

You can get all the nodes of an XElement of a specific type by using the OfType Linq extension on the return value of the Nodes method.

XElement.Nodes().OfType<XText>()

This example gets the value you're looking for, I think:

var xml = 
    @"<root>      
       <sub>maintext1
        <subsub>subtext1</subsub>
        <subsub>subtext2</subsub>
       </sub>          
      </root>";
var xel = XElement.Parse(xml);
var textNodes = xel.Element("sub").Nodes().OfType<XText>();
var mainText1 = textNodes.First().Value;
qxn
  • 17,162
  • 3
  • 49
  • 72