我有一系列来自 Amazon 的复杂 XML 文件显示订单报告。
XML 片段如下:
<Order>
<AmazonOrderID>000-1111111-2222222</AmazonOrderID>
<MerchantOrderID>111-3333333-4444444</MerchantOrderID>
<PurchaseDate>2012-03-02T13:28:53+00:00</PurchaseDate>
<LastUpdatedDate>2012-03-02T13:29:05+00:00</LastUpdatedDate>
<OrderStatus>Pending</OrderStatus>
<SalesChannel>Amazon.com</SalesChannel>
<URL>http://www.amazon.com</URL>
<FulfillmentData>
<FulfillmentChannel>Amazon</FulfillmentChannel>
<ShipServiceLevel>Standard</ShipServiceLevel>
<Address>
<City>Beverly Hills</City>
<State>CA</State>
<PostalCode>90210-1234</PostalCode>
<Country>US</Country>
</Address>
</FulfillmentData>
<OrderItem>
<ASIN>AmazonASIN </ASIN>
<SKU> Internal-SKU</SKU>
<ItemStatus>Pending</ItemStatus>
<ProductName> This is the name of the product </ProductName>
<Quantity>1</Quantity>
<ItemPrice>
<Component>
<Type>Principal</Type>
<Amount currency="USD">19.99</Amount>
</Component>
</ItemPrice>
</OrderItem>
</Order>
我需要对这个文件做的是提取 XML 文档的各个部分,然后对数据做一些事情。
我遇到的问题来自多个订单项目。
以下代码将正确抓取每个节点并将其放入列表项中,但是我不确定如何在 C# 中将这些多个项与相同的订单号相关联。
C# 片段:
List<string> getNodes(string path, string nodeName) {
List<string> nodes = new List<string>();
XDocument xmlDoc = XDocument.Load(path); //Create the XML document type
foreach (var el in xmlDoc.Descendants(nodeName)) {
//for debugging
//nodes.Add(el.Name + " " + el.Value);
//for production
nodes.Add(el.Value);
}
return nodes;
} //end getNodes
该方法调用如下:
List<string> skuNodes = xml.getNodes(@"AmazonSalesOrders.xml", "SKU");
其中 xml 是实例化的类。
进一步解释复杂性:如果每个节点都放入自己的列表中,则列表的长度将保持不变,只要对一个项目进行排序。订购多件商品后,SKU、数量、价格等列表将变长并防止出现简单的循环。
我确信有一个 LINQ to XML 语句可以满足我的需求,但我对 C# 的经验还不够多,无法破解它。
+++++++++++++++++ 编辑+++++++++++++++++++
我正在尝试在网上找到的一些 LINQ 建议。以下看起来很有希望,但正在返回异常:
base {System.SystemException} = {"Object reference not set to an instance of an object."}
代码是:
var query = from xEle in xmlDoc.Descendants(node)
where xEle.Element("AmazonOrderID").Value.ToString() == primaryKey
select new {
tag = xEle.Name.LocalName,
value = xEle.Value
};
我不确定为什么会发生这种情况,节点的变量和主键是在运行时传递的。
如果我设置断点,我可以看到 primaryKey 被正确传递,与节点相同;但是,当我到达:
Dictionary<string, string> ordersByID = new Dictionary<string, string>();
foreach (var CurNode in query) {
ordersByID.Add(CurNode.tag, CurNode.value);
}
我在解析 CurNode 时收到空引用错误。
最佳答案
您可以按照您的想法使用 linq 来实现这一点,这样的事情应该可以工作,如果需要为 itemprice 等添加更多元素。:(其中 ns 是命名空间)
xmlDoc = XDocument.Parse(sr.ReadToEnd());
XNamespace ns = "w3.org/2001/XMLSchema-instance";
var query = from order in xmlDoc.Descendants(ns + "Order")
from orderItem in order.Elements(ns + "OrderItem")
select new
{
amazonOrdeID = order.Element(ns + "AmazonOrderID").Value,
merchantOrderID = order.Element(ns + "MerchantOrderID ").Value,
orderStatus = order.Element(ns + "OrderStatus ").Value,
asin = orderItem.Element(ns + "ASIN").Value,
quantity = orderItem.Element(ns + "quantity").Value
};
使用上述内容,您可以在单行中带回每个亚马逊订单所需的所有信息......