Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get elements without child elements?

Here is my xml:

<Root>  
<FirstChild id="1" att="a">
    <SecondChild id="11" att="aa">
        <ThirdChild>123</ThirdChild>
        <ThirdChild>456</ThirdChild>
        <ThirdChild>789</ThirdChild>
    </SecondChild>
    <SecondChild id="12" att="ab">12</SecondChild>
    <SecondChild id="13" att="ac">13</SecondChild>
</FirstChild>  
<FirstChild id="2" att="b">2</FirstChild>  
<FirstChild id="3" att="c">3</FirstChild>
</Root>

This xml doc is very big and may be 1 GB size or more. For better performance in querying, i want to read xml doc step by step. So, in first step i want to read only "First Child"s and their attributes like below:

<FirstChild id="1" att="a"></FirstChild>  
<FirstChild id="2" att="b">2</FirstChild>  
<FirstChild id="3" att="c">3</FirstChild>

And after that, I maybe want to get "SecondChild"s by id of their parent and so ...

<SecondChild id="11" att="aa"></SecondChild>
<SecondChild id="12" att="ab">12</SecondChild>
<SecondChild id="13" att="ac">13</SecondChild>

How can I do it?

Note: XDoc.Descendants() or XDoc.Elements() load all specific elements with all child elements!

like image 301
Saleh Bagheri Avatar asked Oct 17 '25 01:10

Saleh Bagheri


1 Answers

I suggest creating a new element and copy the attributes.

var sourceElement = ...get "<FirstChild id="1" att="a">...</FirstChild>" through looping, xpath or any method.

var element = new XElement(sourceElement.Name);
foreach( var attribute in sourceElement.Attributes()){
    element.Add(new XAttribute(attribute.Name, attribute.Value));
}
like image 188
LosManos Avatar answered Oct 18 '25 13:10

LosManos



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!