Reputation: 10704
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
Upvotes: 0
Views: 3749
Reputation: 101711
Then instead of this:
new XElement("Barcode", Form1.GetStrings(1).Select(i => new XElement("Barcode", i)))
Use your query directly like this, don't create an extra Barcode
element:
Form1.GetStrings(1).Select(i => new XElement("Barcode", i))
Then your code should look like 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))
));
That will give you the expected output.
Upvotes: 4
Reputation:
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))
));
Upvotes: 0