I am trying to convert an XML to a nested XML with an element's attribute. I googled a lot and looked through some questions and answers here, but I still can't get my mind around it.
I want to group the child node under same author's name using C#, linq to xml.
Sample XML:
<authors>
<author name="John">
<books>
<book type="Children">ABC</book>
</books>
<published> ---<new
<print year="2011"> ---<new
<publisher>Msoft</publisher> ---<new
</print> ---<new
</published> ---<new
</author>
<author name="May">
<books>
<book type="Children">A beautiful day</book>
</books>
<published> ---<new
<print year="2011"> ---<new
<publisher>hardsoft</publisher> ---<new
</print> ---<new
</published> ---<new
</author>
<author name="John">
<books>
<book type="Fiction">BBC</book>
</books>
<published> ---<new
<print year="2013"> ---<new
<publisher>dsney</publisher> ---<new
</print> ---<new
</published> ---<new
</author>
</authors>
Output expect:
<authors>
<author name="John">
<books>
<book type="Children">ABC</book>
<book type="Fiction">BBC</book>
</books>
<published>
<print year="2011">
<publisher>Msoft</publisher>
<publisher>hardsoft</publisher>
</print>
</published>
</author>
<author name="May">
<books>
<book type="Children">A beautiful day</book>
</books>
<published>
<print year="2013">
<publisher>dsney</publisher>
</print>
</published>
</author>
</authors>
If there are additional nodes with attribute need to group under the same author, example should I just add another grouping or select the element from the previous group?
So far, I have tried:
XDocument doc = XDocument.Load(pathtoxmlfile);
var query = from e in doc.Elements("author")
group e by e.Attribute("name").Value into g
select new XElement("author", new XAttribute("name", g.Key),
new XElement("books",
g.Select(x => x.Element("books").Elements("book"))
, new XElement("published",
g.Select(y=>y.Elements("publisher")
)
)
)
);
XElement root = new XElement("authors", query);
It only output me inside and author node with no entry.
<author>
<books>...this part is output as expect...
</books>
<published>
<publisher />
</published>
</author>