Reputation: 137492
In .NET, how do I read the text content from an XElement?
For example, from the XElement
XElement.Parse("<tag>Alice & 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
Reputation: 1238
XElement t= Xelement.Parse("<tag>Alice & Bob<other>cat</other></tag>");
string s = t.toString();
Upvotes: 0
Reputation: 1721
Just because I recently had a similar requirement, I'm offering up:
var x = XElement.Parse("<tag>Alice & 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
Reputation: 75326
XElement t = XElement.Parse("<tag>Alice & Bob<other>cat</other></tag>");
string s = (t.FirstNode as XText).Value;
Upvotes: 13
Reputation: 3261
XElement t= XElement.Parse("<tag>Alice & Bob<other>cat</other></tag>");
string s = t.FirstNode.ToString();
Upvotes: 0
Reputation: 3721
Try following code It might help you..
namespace ConsoleApplication6
{
class Program
{
static void Main(string[] args)
{
var parent = XElement.Parse("<tag>Alice & 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
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