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