Home > DeveloperSection > Forums > Generating Xelement from list of object
john rob

Total Post:108

Points:756
Posted on    January-22-2014 11:43 PM

 C# C# 
Ratings:


 1 Reply(s)
 760  View(s)
Rate this:

My Code

IList<Person> people=new List<Person>();

            people.Add(new Person{Id=1,Name="Nitin"});

        IList<decimal> my=new List<decimal>(){1,2,3};

        IList<int> your=new List<int>(){1,2,3};

        XElement xml = new XElement("people",

                            from p in people

                            select new XElement("person", new XAttribute("Id", "Hello"),

                                        new XElement("id", p.Id),

                                        new XElement("Mrp", my.Contains(1) ? string.Join(",",my):"Nitin"),

                                       new XElement("Barcode", Form1.GetStrings(1).Select(i => new XElement("Barcode", i)))

                                        ));

        MessageBox.Show(xml.ToString());

GetStrings only returns int from 1 to 4

Output

<people>

  <person Id="Hello">

    <id>1</id>

    <Mrp>1,2,3</Mrp>

    <Barcode>

      <Barcode>1</Barcode>

      <Barcode>2</Barcode>

      <Barcode>3</Barcode>

      <Barcode>4</Barcode>

    </Barcode>

  </person>

</people>

But I want output as

 <people>

          <person Id="Hello">

            <id>1</id>

            <Mrp>1,2,3</Mrp>

            <Barcode>1</Barcode>

              <Barcode>2</Barcode>

              <Barcode>3</Barcode>

              <Barcode>4</Barcode>

           </person>

</people>

Any Solutions



Pravesh Singh

Total Post:411

Points:2881
Posted on    January-23-2014 12:54 AM

Hi John,

Try this :

XElement xml = new XElement("people",

                    from p in people

                    select new XElement("person", new XAttribute("Id", "Hello"),

                               new XElement("id", p.Id),

                               new XElement("Mrp", my.Contains(1) ? string.Join(",",my):"Nitin"),

                               Form1.GetStrings(1).Select(i => new XElement("Barcode", i))

                         ));


Don't want to miss updates? Please click the below button!

Follow MindStick