ADO Linq to xml
I am writing a prgm that via the ADO datacontext, I am running a query on the database that uses a group clase and returns an xml document. I am able to get the xml to work, but the XAttribute("pub_id", from p in g select new { p.Pubs_id })
is giving :
System.Linq.Enumerable+WhereSelectEnumerableIterator`2[Pubs.BookStore+BookResults,<>f__AnonymousType1`1[System.String]]
below is the code:
XDocument xdoc = new XDocument(new XElement("reports",
from b in bookResults
group b by b.Title1 into g
select new XElement("book",
new XAttribute("pub_id", from p in g select new { p.Pubs_id }),
new XElement("Title", g.Key),
from bk in g
select new XElement("Name", new XAttribute("au_id", bk.Au_id), bk.Name))
)
xdoc.Save("Books.xml");
sample xml output desired ( using pubs sample db)
<reports>
<book pub_id="1389">
<Title>The Busy Executive's Database Guide</Title>
<Name au_id="409-56-7008">Bennet,Abraham</Name>
<Name au_id="213-46-8915">Green,Marjorie</Name>
</book>
<book pub_id="0877">
<Title>Fifty Years in Buckingham Palace Kitchens</Title>
<Name au_id="648-92-1872">Blotchet-Halls,Reginald</Name>
</book>
<book pub_id="0877">
<Title>The Gourmet Microwave</Title>
<Name au_id="722-51-5454">DeFrance,Michel</Name>
<Name au_id="899-46-2035">Ringer,Anne</Name&开发者_如何学JAVAgt;
</book>
You're providing a query returning a sequence as the value of an attribute. My guess is that you expect there to be a single result, in which case you just need to change it to:
new XAttribute("pub_id", (from p in g select new { p.Pubs_id }).Single())
Or even:
new XAttribute("pub_id", (from p in g select p.Pubs_id).Single())
It's not really clear whether that is what you're expecting though - but that's the problem. LINQ to XML is calling ToString
on your query, and you're seeing the result of that. Change the second constructor argument to something which gives a single value, however you need to do it.
I suspect you'll find that if you indent your code more clearly, it'll make it more obvious what's going on - at the moment it's not really clear just from looking at it. I would rewrite your query as provided in the question as:
from b in bookResults
group b by b.Title1 into g
select new XElement("book",
new XAttribute("pub_id", from p in g select new { p.Pubs_id }),
new XElement("Title", g.Key),
from bk in g
select new XElement("Name", new XAttribute("au_id", bk.Au_id), bk.Name))
)
精彩评论