Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have an xml from which I am trying to extract some information through LINQ query.
The format of the xml file looks like the following:

<TopNode>
  <Sample name="Tom" id="0" batch="1">
    <Sequences>
      <NextItem id="10">Stand1 &gt;</NextItem>
      <PreviousItem id="9">Stand2 &gt;</PreviousItem>
    </Sequences>
  </Sample>
  <Sample name="Hill" id="1" batch="1">
    <Sequences>
      <NextItem id="1">Stand1 &gt;</NextItem>
      <NextItem id="2">Stand3 &gt;</NextItem>
      <PreviousItem id="3">Stand4 &gt;</PreviousItem>
    </Sequences>
  </Sample>
.
.
.
</TopNode>

I have to get a list of attributes of both NextItem and PreviousItem from the query. For this, I defined a class to get my results.

public class Extract
{
public string name 
{
get;
set;
}
public int _id
{
get;
set;
}
}

LINQ Query (foreach Sample node, get the PreviousItem and NextItem content in class object):

var EnumerableContent = from item in XElement.Load("file.xml").Elements("NextItem")
              select ???...

The problem is how do I pass the data to the class objects here in the above query for each Sample node.
. Secondly, the above will only get me NextItem nodes. How do I write the query for both NextItem and PreviousItem?

EDIT On the whole, I have to get an IEnumerable for each for each of the Sequence nodes, and then return the overall IEnumerable from thie query.

EDIT2 Assigning key here is giving me this error. Query below

var mapping = XDocument.Load("file.xml")
                          .Descendants("Sequences")
                          .Select(n => n.Descendants("PreviousItem")
                              .Union(n.Descendants("NextItem"))
                              .Select(n1 => new Extract { _id = (int)n1.Attribute("id"), Name = n1.Value })
                              ).ToDictionary<IEnumberable<Menu>, int>(key => key._id);//and further converting this dictionary to sorted dictionary (sorted accordign to keys)
share|improve this question

3 Answers

up vote 1 down vote accepted
var xDoc = XDocument.Load(....);
var result = xDoc.Descendants("NextItem")
  .Union(xDoc.Descendants("PreviousItem"))
  .Select(n => new {ID = n.Attribute("id").Value, Name =n.Name, Value =n.Value });

--EDIT--

var result = XDocument.Load(....)
            .Descendants("Sequences")
            .Select(n=> n.Descendants("NextItem")
                 .Union(n.Descendants("PreviousItem"))
                 .Select(n2 => new { ID = n2.Attribute("id").Value, Name = n2.Name, Value = n2.Value })
            );
share|improve this answer
This will give me the IEnumerable for each of the NextItem, and PreviousItem in the xml. What I actually want is that, for each of the Sequence nodes, I should generate an enumberable and then return an overall IEnumberable of the above. I hope I am abe to convey the problem. ;-/ – Cipher Apr 3 '12 at 9:09
@Cipher I updated the answer, I hope I understood you correctly. – L.B Apr 3 '12 at 9:25
Thanks! Yes, but the reason I wrote an Extarct Class was that I wanted to convert the result into a dictionary afterwards i.e .ToDictionary<TKey, TValue> where TValue could be the Extract class's IEnumberable. In the above statement, I am not able to do .Select(new Menu{ SeekPoint = (int)n1.Attribute("time"), ItemText = n1.Value }) – Cipher Apr 3 '12 at 9:58
Actually, edited my question. See EDIT2 for going a bit further to the problem. – Cipher Apr 3 '12 at 10:06
@Cipher then, don't convert it to Dict. just append a ToList and use as a list. – L.B Apr 3 '12 at 10:51
show 1 more comment

I'm not sure I understood the question, but you can easily take element/attribute value inside LINQ to XML select statement:

var EnumerableContent = from item in XElement.Load("file.xml").Elements("NextItem")
              select new Extract() { name = item.Value, _id = (int)item.Attribute("id") }
share|improve this answer
I am getting only NextItem elements, but I want to modify the query get the same thing for the PreviousItem nodes too. ;-/ The problem is that I want to get a separate IEnumerable of PreviousItem and NextItem for each of the Sequence nodes in xml, and return the overall IEnumberable – Cipher Apr 3 '12 at 9:02

hi i think this is what you expect.

List<XElement> lstXElements = new List<XElement>();
        lstXElements.AddRange(GetDescendants("NextItem"));
        lstXElements.AddRange(GetDescendants("PreviousItem"));

        List<Extract> lstExtract = new List<Extract>();

        foreach (XElement objElement in lstXElements)
        {
            Extract objExtract = new Extract();
            objExtract._id = Convert.ToInt32(objElement.Attribute("id").Value);
            objExtract.name = (objElement.Name).LocalName;
            lstExtract.Add(objExtract);
        }
List<XElement> GetDescendants(string strDescentName)
    {
        return ((XDocument.Load(Server.MapPath("XMLFile1.xml"))
            .Descendants(strDescentName))
            ).ToList<XElement>();
    }
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.