给出两个这样的
XML文件:
<Customers>
<Customer CustomerID="alc">Alice</Customer>
</Customer>
和
<Orders>
<Order OrderID="001" CID="alc">apple</Order>
</Orders>
现在我需要加入这两个XML文件并使用内部联接创建一个新文件:
<Result>
<Join>
<Customer CustomerID="alc">Alice</Customer>
<Order OrderID="001" CID="alc">apple</Order>
</Join>
</Result>
我有这个问题:
var result = new XElement("Result",
from customer in XElement.Load("Customers.xml").Elements("Customer")
join order in XElement.Load("Orders.xml").Elements("Order")
on
(string)customer.Attribute("CustomerID")
equals
(string)order.Attribute("CID")
select new XElement("Join",
new XElement("Customer", (string)customer.Element("Customer"),
new XAttribute("CustomerID", (string)customer.Attribute("CustomerID"))),
new XElement("Order", (string)order.Element("Order"),
new XAttribute("OrderID", (string)order.Attribute("OrderID")),
new XAttribute("CID", (string)order.Attribute("CID")))));
result.Save("result.xml");
有了这个我无法获得数据“爱丽丝”和“苹果”.结果是这样的:
<Result>
<Join>
<Customer CustomerID="alc" />
<Order OrderID="001" CID="alc" />
</Join>
</Result>
我想也许(字符串)customer.Element(“Customer”)和(字符串)order.Element(“Order”)有一些问题,我不知道如何修改它们.
最佳答案 您只需
cast an element to a string
即可获得其文本值:
select new XElement("Join",
new XElement("Customer", (string)customer,
new XAttribute("CustomerID", (string)customer.Attribute("CustomerID"))),
new XElement("Order", (string)order,
new XAttribute("OrderID", (string)order.Attribute("OrderID")),
new XAttribute("CID", (string)order.Attribute("CID")))));