Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XDocument Elements return null

Tags:

c#

xml

linq

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

like image 804
João Horta Avatar asked Jun 07 '26 11:06

João Horta


1 Answers

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());
like image 179
Alex Filipovici Avatar answered Jun 10 '26 15:06

Alex Filipovici



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!