2011-08-28 111 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