Colonel Panic
Colonel Panic

Reputation: 137492

Read text content from XElement

In .NET, how do I read the text content from an XElement?

For example, from the XElement

XElement.Parse("<tag>Alice &amp; Bob<other>cat</other></tag>")

I would like the string 'Alice & Bob'


I tried element.Value but that returns 'Alice & Bobcat' :(

Upvotes: 18

Views: 17007

Answers (6)

Lokiare
Lokiare

Reputation: 1238

XElement t= Xelement.Parse("<tag>Alice &amp; Bob<other>cat</other></tag>");
string s = t.toString();

Upvotes: 0

jimbobmcgee
jimbobmcgee

Reputation: 1721

Just because I recently had a similar requirement, I'm offering up:

var x = XElement.Parse("<tag>Alice &amp; Bob<other>cat</other></tag>")
var text = string.Concat(x.Nodes().OfType<XText>().Select(t => t.Value));

Will not capture text content of child nodes, but will concatenate all untagged text nodes in the current element.

Upvotes: 8

cuongle
cuongle

Reputation: 75326

 XElement t = XElement.Parse("<tag>Alice &amp; Bob<other>cat</other></tag>");
 string s = (t.FirstNode as XText).Value;

Upvotes: 13

Frank59
Frank59

Reputation: 3261

XElement t= XElement.Parse("<tag>Alice &amp; Bob<other>cat</other></tag>");
string s = t.FirstNode.ToString();

Upvotes: 0

MMK
MMK

Reputation: 3721

Try following code It might help you..

namespace ConsoleApplication6
{
    class Program
    {
        static void Main(string[] args)
        {
            var parent = XElement.Parse("<tag>Alice &amp; Bob<other>cat</other></tag>");
            var nodes = from x in parent.Nodes()
                            where x.NodeType == XmlNodeType.Text
                            select (XText)x;

            foreach (var val in nodes)
            {
                Console.WriteLine(val.Value);
            }
            Console.ReadLine();
        }
    }
}

Upvotes: 1

Ricardo Rodriguez
Ricardo Rodriguez

Reputation: 1090

Using element.FirstNode you can get the raw content that you have inside the element, "Alice & Bob", so you only need to "unescape" the ampersand and you will get the result that you are expecting.

Upvotes: 1

Related Questions