gpt4 book ai didi

C# LINQ to XML : how to join Xml Data

转载 作者:数据小太阳 更新时间:2023-10-29 02:10:21 27 4
gpt4 key购买 nike

给定两个像这样的 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");

用这个我无法获得数据“Alice”和“apple”。结果是这样的:

<Result>
<Join>
<Customer CustomerID="alc" />
<Order OrderID="001" CID="alc" />
</Join>
</Result>

我想也许 (string)customer.Element("Customer")(string)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")))));

关于C# LINQ to XML : how to join Xml Data,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31890713/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com