2011-08-28 114 views
0

我正在写一个prgm,通过ADO datacontext,我在使用group clase的数据库上运行查询并返回一个xml文档。我能够获得XML工作,但XAttribute("pub_id", from p in g select new { p.Pubs_id })所赐:ADO Linq to xml

System.Linq.Enumerable+WhereSelectEnumerableIterator`2[Pubs.BookStore+BookResults,<>f__AnonymousType1`1[System.String]] 
下面

是代码:

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");  

示例XML输出所需的(使用pubs示例数据库)

<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> 
    </book> 
+0

你说的话让我思考,看来我需要PUB_ID为重点的一部分,我做了以下,并通过新的工作 – SKatz

+0

B组{b.Title1,b.Pubs_id} into g – SKatz

+0

thnks for your help – SKatz

回答

2

您提供的查询返回一个序列作为属性的值。我的猜测是,你认为会有一个结果,在这种情况下,您只需将其更改为:

new XAttribute("pub_id", (from p in g select new { p.Pubs_id }).Single()) 

甚至:

new XAttribute("pub_id", (from p in g select p.Pubs_id).Single()) 

这不是真的清楚是否你期望什么 - 但这就是问题所在。 LINQ to XML在你的查询中调用ToString,你会看到结果。将第二个构造函数参数更改为给出单个值的东西,但是您需要这样做。

我怀疑你会发现,如果你更清楚地缩进你的代码,它会使事情变得更加明显 - 目前从查看它不是很清楚。在这个问题作为我重写查询:

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)) 
) 
+0

感谢您的快速回复,通过执行上述操作,我得到一个调试错误:序列包含多个元素 – SKatz

+0

@Satatz:好的,所以有两个或更多的元素...你想要什么值的属性?了解这个问题很重要 - 直到你这样做,你将无法解决这个问题。问题是你目前正试图为一个属性提供多个值 - 但一个属性只有一个值。我现在要睡觉了,但如果所有这些都不能帮助你,请留下更多细节,我会在早上帮助你。 –

+0

thnks,我添加了输出的xml sippet – SKatz