The Author Online Book Forums are Moving

The Author Online Book Forums will soon redirect to Manning's liveBook and liveVideo. All book forum content will migrate to liveBook's discussion forum and all video forum content will migrate to liveVideo. Log in to liveBook or liveVideo with your Manning credentials to join the discussion!

Thank you for your engagement in the AoF over the years! We look forward to offering you a more enhanced forum experience.

shailesh_buzz (2) [Avatar] Offline
#1
Hi,

Suppose i have XML like,





<SubMenu>

<MenuItem />

<MenuItem />



<SubMenu>

<MenuItem />

<MenuItem />

</SubMenu>



</SubMenu>





if I used Linq with C#:


var list = from item in menuxml.Descendents("MenuItem")

select item



If menuxml points to SubMenu Element. then query returns all MenuItems including MenuItems of inner SubMenu Element. I want to acces only Level 1 MenuItems (i.e. MenuItems in bold font) How can i write Linq query to get only those elements. I Can not write "where item.Parent.Name != "SubMenu" because the parent of inner MenuItems and outer have same name SubMenu.

Please suggest,


Thanks
shailesh_buzz (2) [Avatar] Offline
#2
Re: How to get Level 1 child Items
Using Elements has solved the problem. It was little bit confusing, but now working.



I tried Elements before. But i was doing somthing wrong and was giving all elements even sub elements of inner element node (SubMenu)

But selecting root element using node.Element("SubMenu") solved the problem.

Here is my code:



Suppose XML is:

<Tree>

<SubMenu>
<MenuItem />
<MenuItem />

<MenuItem>

<SubMenu>
....................<MenuItem />
....................<MenuItem />
</SubMenu>
</MenuItem>



</Tree>


I want to get only MenuItem elements which are in Bold.

XDocument doc = XDocument.Parse(MenuXml);



var menudoc = from item in doc.Descendents("Tree")

select item



suppose, menudoc have element tree.



now if i use,

menudoc.Descendents("MenuItem") then it will return all MenuItem element (MenuItem inside inner SubMenu tag also)



But to get MenuItem at level 1 (In bold font) use

menudoc.Element("SubMenu").Elements()



Also check link:

http://msdn.microsoft.com/en-us/library/bb675159.aspx



Thanks,