我有一系列来自 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 时收到空引用错误。