user319249
user319249

Reputation: 145

Grabbing text of a single element in XDocument (C#)

I have an XML document that looks like

<a>foo<b>bar</b></a>

Creating an XDocument with the above XML, then using

doc.Descendants(new XName("a")).First().Value 

results in "foobar" rather than "foo" as I expected.

How can I just get the value of <a /> without subtracting the value of <b /> from <a />?

Thanks in advance!

Upvotes: 0

Views: 60

Answers (3)

vcsjones
vcsjones

Reputation: 141588

<a> actually contains two nodes, a text node and the b element. You can filter a children to of type XText:

var xml = "<a>foo<b>bar</b></a>";
var document = XDocument.Parse(xml);
Console.WriteLine(document.Descendants("a").First().Nodes().OfType<XText>().First().Value);

Upvotes: 3

Squiggle
Squiggle

Reputation: 2597

This isn't quite an answer, but I would question the validity of your XML in this example. Consider the XML-compatible markup for a HTML paragraph with a hyperlink:

<p>Go to the <a href="http://stackoverflow.com">StackOverflow</a> front page</p>

The contents of the paragraph (the value of <p> ) is still the full sentence rather than just the words "go to the ".

Also, given your example, what happens if you have more text after <b>bar</b>?

Upvotes: 0

Daniel Filipov
Daniel Filipov

Reputation: 325

Seem kind of invalid XML. Maybe you should try attribute ... something like this

<a name="foo">
<b>bar</b>
</a>

Upvotes: 0

Related Questions