2015-08-08 98 views
2

我正在嘗試做左外部加入兩個XML並獲得另一個XML(不是集合!)作爲輸出,但LINQ的查詢'進入'似乎只提取了所有原始標籤和屬性的值而不是全部元素。C#LINQ左外部加入XML無法正常工作

XML1看起來是這樣的:

<tag> 
    <abc id="zxy">tiger</abc> 
    <abc id="zzz">rabbit</abc> 
</tag> 

XML2

<tag> 
    <aaa attr1="1" attr2="zzz">value1</aaa> 
    <aaa attr1="2" attr2="zxc">value2</aaa> 
</tag> 

我在C#代碼:

var que= from first in xml1 
     join second in xml2 
     on (string)first.Attribute(attr1) equals (string)second.Attribute(attr2) into temp 
     from tmpL in temp.DefaultIfEmpty() 
     orderby (string)first.Attribute(attr1)//, (string)tmpL.Attribute(attr2) -- this one isn't working because it's not an element 
     select new XElement("child", first, tmpL == null ? String.Empty : (string)tmpL); 

var final= new XDocument(new XElement("parent", que)); 

這就是我得到結合兩個以上使用該代碼的XML:

<parent> 
    <child> 
    <abc id="zxy">tiger</abc>value1</child> 
    <child> 
    <abc id="zzz">rabbit</abc>value2</child> 
</parent> 

正如你可以看到它是一個無效的XML與value1和值2粘到同級元素,而應該在自己的原標籤包裹(與原來的屬性):<aaa attr1="1" attr2="zzz">value1</aaa><aaa attr1="2" attr2="zxc">value2</aaa>水漲船高。

因此我無法使用.Attribute()和其他東西。 另外我不能只在新創建的元素中插入這些值,因爲我需要xml2中原始元素的屬性。

你能幫我拿到下面的XML嗎?

<parent> 
    <child> 
    <abc id="zxy">tiger</abc> 
    <aaa attr1="1" attr2="zzz">value1</aaa> 
    </child> 
    <child> 
    <abc id="zzz">rabbit</abc> 
    <aaa attr1="2" attr2="zxc">value2</aaa> 
    </child> 
</parent> 

回答

1

「..但LINQ的查詢‘到’似乎只提取值,但所有的原標籤不完整的元素和屬性」

你居然得到了XElement小號如預期的那樣,但之後將其明確地轉換爲string,這導致僅保留字符串值,這裏:

select new XElement("child", first, tmpL == null ? String.Empty : (string)tmpL); 

刪除鑄造,簡單地傳遞null代替String.Empty當你什麼都不想要成爲新創建的child元素的子:

select new XElement("child", first, tmpL == null ? null : tmpL); 

或者只是通過tmpL無論是null與否,其產生的等效但更清潔的聲明:

select new XElement("child", first, tmpL); 
+0

非常感謝!有效!唯一剩下的就是orderby,我指出了我的初始評論:'orderby(string)first.Attribute(attr1)//,(string)tmpL.Attribute(attr2) - 這個不起作用,因爲它不是element'。我在'tmpL.Attribute(attr2)'之前刪除了'string',但它仍然說它不是對象的一個​​實例有沒有一種方法可以用它來排序? –