Click here to Skip to main content
15,884,838 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
xml file is like this:
for example I want to access elemnts inside of Child1
HTML
<main>
 <child1>
    <part1>
       <a></a>
       
    </part1>
    <part1>
       <a></a>
       
    </part1>
 </child1>
 <child2>
    <part2>
       <c></c>
       <d></d>
    </part2>
 </child2>
 <child3>
    <part3>
    </part3>
 </child3>
</main>


before for below xml I wrote below code and that was OK.
HTML
<child1>
   <part1>
      <a></a>
      
   </part1>
   <part1>
      <a></a>
      
   </part1>
</child1>

C#
var doc = XElement.Load(txtRecivePath.Text);
                var ms = doc.Elements("part1").ToList();
                fields = ms.Select(s => new Class_PersonelInfo()
                {
                    prsnlCod = s.Element("a").Value;
                }
Posted
Updated 15-Feb-15 15:08pm
v4
Comments
Zoltán Zörgő 15-Feb-15 14:30pm    
What exactly would you like to see after parsing your input?
mit62 15-Feb-15 14:37pm    
I just want to know how can I access to values inside childe1.
this code was wrong:
var ms = doc.Elements("main").Elements("child1").ToList();
fields = ms.Select(s => new Class_PersonelInfo()
{
prsnlCod = s.Element("a").Value;
}

Use doc.Descendants("child1"); instead.
 
Share this answer
 
Comments
Thomas Daniels 15-Feb-15 15:02pm    
Not exactly. child1 can be accessed fine through Elements, because it's a direct child element of main. The problem arises when fetching all a tags, because these are not a direct child of the child1 elements. Please see my answer, Solution 2.
Zoltán Zörgő 15-Feb-15 15:05pm    
Yes, it works in that specific case, but you still need Descendants... so...
You use s.Element("a"), but there are no a elements directly in your child1 tag. There are only a tags in your part1 tag.

To access the a-tags, you can use s.Descendants:
C#
var doc = XElement.Parse(xml);
var ms = doc.Elements("child1").ToList();
var allATags = ms.Select(s => s.Descendants(XName.Get("a")))
    .SelectMany(x => x)
    .ToList();

ms.Select returns a collection of collections of XElements here. SelectMany merges them all into one, and ToList converts it to a list. Now allATags contains all a-tags within child1-tags.
 
Share this answer
 
v3
Try this...

HTML
var xdoc= XElement.Parse(xml);
var app = from p in xdoc.Elements("a")
          select p;
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900