views:

109

answers:

2

i have a xml document like this:

<ns:a xmlns:ns="http://NS1"&gt;
  <ns:b>
    <c xmlns="http://differentNS"&gt; c_text </c>
    <x xmlns="http://differentNS"&gt; Wanted </x>
    <d xmlns="http://differentNS"&gt; d_text </d>
  </ns:b>
</ns:a>

Now i want to use linq to read the element's "x" inner text.

A: 

You should be able to do something like this:

var xDocument = XDocument.Load(yourdocumenthere);
var myvalue = xDocument.Element("ns:a").element("ns:b").element("c").value;

This isn't using link, but is still very simple.

Dofs
Yes, it's simple but only works with no namespaces. If i write "ns:a" i receive the exception "The ':' character, hexadecimal value 0x3A, cannot be included in a name."
Nabo
+1  A: 

Here's a possible implementation using LINQ to XML:

var doc = XDocument.Parse("<ns:a xmlns:ns='http://NS1'&gt;&lt;ns:b&gt;&lt;c xmlns='http://differentNS'&gt;c_text&lt;/c&gt;&lt;x xmlns='http://differentNS'&gt;Wanted&lt;/x&gt;&lt;d xmlns='http://differentNS'&gt;d_text&lt;/d&gt;&lt;/ns:b&gt;&lt;/ns:a&gt;");

XNamespace ns = "http://differentNS";
var result = doc.Descendants(ns + "x").Single().Value

Related resources:

Enrico Campidoglio
doc.Descendants returns an IEnumerable<XElement> which don't have the Value property. What cast should i do?
Nabo
You are right. You need to select the single XElement in the list in order to extract the value. I updated my answer.
Enrico Campidoglio