I want to create the following the xml
<BookStore>
<Book>
<Name></Name>
<Author></Author>
<Price></Price>
</Book>
<Book>
<Name></Name>
<Author></Author>
<Price></Price>
</Book>
</BookStore>
From
List<XElement> Book= xdoc.XPathSelectElements("s0:Name| s0:Author| s0:Price", namespaceManager).ToList();
I am struck in the following place :
XNamespace s0 = "urn:service.Bookstore.com";
XElement root=new XElement(s0 + "BookStore",
new XElement("Book",Book,
);
XDocument result = new XDocument(root);
But this gives the xml structure to be
<BookStore>
<Book>
<Name></Name>
<Author></Author>
<Price></Price>
<Name></Name>
<Author></Author>
<Price></Price>
</Book>
</BookStore>
Please help me in getting the expected output.Since the base xml structure looks like this
<BookStore>
<Book>
<Name></Name>
<Author></Author>
<Price></Price>
<Name></Name>
<Author></Author>
<Price></Price>
</Book>
</BookStore>
But I want it as two separate instances of
It sounds like you basically need to take the list of elements and group them into groups of 3 elements, putting each group in a Book
element:
// The name/author/price elements you're already getting
var elements = ...;
var groups = elements.Select((value, index) => new { value, index })
.GroupBy(pair => pair.index / 3, pair => pair.value);
XNamespace s0 = "urn:service.Bookstore.com";
XDocument result = new XDocument(new XElement(s0 + "BookStore",
groups.Select(g => new XElement("Book", g))));
See more on this question at Stackoverflow