gpt4 book ai didi

c# - 如何使用 LINQ 解析 XML header 和嵌套部分

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

XElement documentRoot = XElement.Parse(@"<OrdersReport Date='2012-08-01'>
<SettingHeader>
<SettingId>1</SettingId>
</SettingHeader>
<Client>
<ClientId>1</ClientId>
<Orders>
<Order>
<OrderNumber>1</OrderNumber>
<ShipAddress>123 Main St.</ShipAddress>
<ShipCity>MyCity</ShipCity>
<ShipState>AZ</ShipState>
</Order>
<Order>
<OrderNumber>2</OrderNumber>
<ShipAddress>111 Main St.</ShipAddress>
<ShipCity>OtherCity</ShipCity>
<ShipState>AL</ShipState>
</Order>
<OrderCancelled>
<OrderNumber>3</OrderNumber>
<ShipAddress>222 Main St.</ShipAddress>
<ShipCity>CancelledCity</ShipCity>
<ShipState>AL</ShipState>
</OrderCancelled>
</Orders>
<Returns>
<Amount>
<OrderId>2</OrderId>
<OrderId>3</OrderId>
<OrderId>21</OrderId>
</Amount>
</Returns>
</Client>
<Client>
<ClientId>2</ClientId>
</Client>
</OrdersReport>");

代码:

        var orders = documentRoot.Descendants("Order")
.Concat(documentRoot.Descendants("OrderCancelled"))
.Select(x => new
{
OrderNumber = (int)x.Element("OrderNumber"),
ShipAddress = (string)x.Element("ShipAddress"),
ShipCity = (string)x.Element("ShipCity"),
ShipState = (string)x.Element("ShipState")
});

foreach (var o in orders)
{
Console.WriteLine(o.OrderNumber + " " + o.ShipAddress + " "
+ o.ShipCity);
}

输出:

1 123 Main St. MyCity
2 111 Main St. OtherCity
3 222 Main St. CancelledCity
3 222 Main St. CancelledCity

如何像下面的输出那样附加 ClientIdSettingId

目标输出:

1 123 Main St. MyCity ClientId 1 SettingId 1
2 111 Main St. OtherCity ClientId 1 SettingId 1
...

最佳答案

试试这个:

var orders = doc.Descendants("Order").Select(x => new
{
OrderNumber = (int)x.Element("OrderNumber"),
ShipAddress = (string)x.Element("ShipAddress"),
ShipCity = (string)x.Element("ShipCity"),
ShipState = (string)x.Element("ShipState"),
ClientId = (int)x.Ancestors("Client").First().Element("ClientId"),
SettingId = (int)doc.Descendants("SettingId").First(),
});

关于c# - 如何使用 LINQ 解析 XML header 和嵌套部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13260131/

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