tags:

views:

59

answers:

1

Hi I am new to LINQ

I have an xml in the following format

   "<root>"
   "<page>"
   "<title>text</title>"
   "<text attrib1="1">some text</text>"
   "<text attrib1="2">some text</text>"
   "<text attrib1="3">some text</text>"
   "<text attrib1="4">some text</text>"

   "</page>"

   "<page>"
   "<title>text</title>"
   "<text attrib1="1">some text</text>"
   "<text attrib1="2">some text</text>"
   "<text attrib1="3">some text</text>"
   "<text attrib1="4">some text</text>"

   "</page>"
  "</root>"

ignore " "

now i want the resultant xml like this

      "<root>"
     "<title>text</title>"
     "<text attrib1="4">some text</text>"
     "<title>text</title>"
     "<text attrib1="4">some text</text>"
     "</root>"

can this be achieved in one query? I tried the following by using two queries

        var titleElms =
            from t in allElements
            select
                new
                {
                    Title = t.Element("title")
                };

        var textElms =
            from t in allText
            where (string)t.Attribute("attrib1").Value == "4"
            select
            t;

I am not happy with it. So is there any other approach? pls help.

A: 

Hi,

I'm don't think this will give you exactly what you want as the query will result in an Ienumerable object. Meaning where you want a single object with lots of title and text fields. This will return an object with title and text being objects within an Ienumerable object.

so in your example you will have an object with two object, each of these anonymous objects now holding the title and text. once you have this, you can build up the xml the way you want. It's not really that much different from your solution but as requested, it will give you one linq query to work with. Or at the very least give you an idea to build on.

    XElement Results = XElement.Load("c:\\test.xml"); //load you xml
    XNamespace NameSpace = Results.Name.Namespace;
    var xe = (from page in Results.Elements(NameSpace + "page")
              let  title = page.Elements(NameSpace+"title")                      
              let text = page.Elements(NameSpace+"text").Where(a=>a.Attribute("attrib1").Value.Equals("4"))   
              where text.Count() > 0 
        //the where is simply to remove any unncessary data 
        //if there was ever a page that didn't have attrib1 = 4

            select new {title, text});

Hope this, at least, gives you a couple new ideas

Kamal
Thanks Kamal... :)
Amit