João Horta
João Horta

Reputation: 43

XDocument Elements return null

I have a xml and i am trying to get the elements of a particular xname so im trying to do something like...

XDocument doc = XDocument.Load("C://some.xml");
XDocument subDoc = new XDocument(doc.Elements("data"));

but in subDoc no elements are returned, and i know i have a element named data, i have tried with the namespace too but not returning any element.

Im wonder if i can get a XDocument only with data (including) and his childs.

some.xml

<chart xmlns="http://www.somenamespace.com">
  <data>
    <table>
      <columns>
        <column id="001" label="A"/>
        <column id="002" label="B"/>
        <column id="003" label="C"/>
        <column id="004" label="D"/>
      </columns>
      <rows>
        <row>
          <cell>
            <float value="30"/>
          </cell>
          <cell>
            <float value="35"/>
          </cell>
          <cell>
            <float value="15"/>
          </cell>
          <cell>
            <float value="18"/>
          </cell>
        </row>
      </rows>
    </table>
  </data>
 <render />
</chart>

someone can Help?

Thanks

Upvotes: 3

Views: 3906

Answers (2)

Alex Filipovici
Alex Filipovici

Reputation: 32561

Add the System.Linq namespace directive to the top of your file:

using System.Linq;

And try this:

XDocument doc = XDocument.Load("c:\\some.xml");
XName name = XName.Get("data", doc.Root.GetDefaultNamespace().NamespaceName);
XDocument subDoc = new XDocument(doc.Descendants(name).First());

Upvotes: 7

ΩmegaMan
ΩmegaMan

Reputation: 31616

Your direct element node is probably not "data"...try descendants instead

doc.Descendants("data");

Upvotes: 1

Related Questions