2015-08-08 65 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',但它仍然说它不是对象的一个​​实例有没有一种方法可以用它来排序? –