I have a number of complex XML files from Amazon showing order reports.
The XML fragment is as follows:
<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>
What I need to do with this file is to extract the various parts of the XML document, and then do a few things with the data.
The problem I am facing consists of several order items.
The following code will correctly grab each node and put it in a list item, however I'm not sure how to associate these multiple items with the same order number in C #.
C # snippet:
List<string> getNodes(string path, string nodeName) { List<string> nodes = new List<string>(); XDocument xmlDoc = XDocument.Load(path);
The method is called as:
List<string> skuNodes = xml.getNodes(@"AmazonSalesOrders.xml", "SKU");
where xml is an instance of the class.
To further explain the complexity: if each node is placed in its own list, the length of the list will be constant if only one item is ordered. After ordering multiple items, SKU lists, quantity, price, etc. Get longer and prevent an easy cycle.
I'm sure there is a LINQ to XML statement that can do what I need, but I'm not so close to experience that C # can crack it.
+++++++++++++++ EDIT ++++++++++++++++++++
I am trying to use some LINQ suggestions that I found on the Internet. The following looks promising, but returns an exception:
base {System.SystemException} = {"Object reference not set to an instance of an object."}
the code:
var query = from xEle in xmlDoc.Descendants(node) where xEle.Element("AmazonOrderID").Value.ToString() == primaryKey select new { tag = xEle.Name.LocalName, value = xEle.Value };
I'm not sure why this is happening, the node and primary key variables are passed at runtime.
If I set breakpoints, I see that primaryKey is passed correctly, the same with node; however, when I get to:
Dictionary<string, string> ordersByID = new Dictionary<string, string>(); foreach (var CurNode in query) { ordersByID.Add(CurNode.tag, CurNode.value); }
I get a null link error as it parses CurNode.