我正在尝试做左外部加入两个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',但它仍然说它不是对象的一个实例有没有一种方法可以用它来排序? –