Get Child Node value using parent Node in XML

2.8k Views Asked by At

How to Get the Value of the node by using the parent tag name.

Here is my XML format.

<ListOrderItemsResponse xmlns="https://mws.amazonservices.com/Orders/2013-09-01">
 <ListOrderItemsResult>
   <AmazonOrderId>Order Id</AmazonOrderId>
 <OrderItems>
   <OrderItem>
     <ASIN>Asin Value</ASIN>
     <SellerSKU>SKU</SellerSKU>
     <OrderItemId>SKU Value</OrderItemId>
     <Title>Product Title</Title>
     <QuantityOrdered>1</QuantityOrdered>
     <QuantityShipped>0</QuantityShipped>
     <ItemPrice>
         <CurrencyCode>INR</CurrencyCode>
         <Amount>30.00</Amount>
     </ItemPrice>
     <ShippingPrice>
        <CurrencyCode>INR</CurrencyCode>
        <Amount>5.00</Amount>
     </ShippingPrice>
  </OrderItem>
</OrderItems>
</ListOrderItemsResult>

How to get Item Price Amount and Shipping Price Amount.

Here i tried so far..

Method 1:

XmlNode node12 = xd1.SelectSingleNode("/ListOrderItemsResponse[@*]/ListOrderItemsResult/OrderItems/OrderItem/ItemPrice");
string id = node12["Amount"].InnerText;

Method 2:

int i = 0;
                XmlNodeList nodeAMT = xd1.GetElementsByTagName("Amount");
                string[] AMT = new string[TotalCount];
                foreach (XmlElement node in nodeAMT)
                {
                    AMT[i] = node.InnerText;
                    i++;
                }

How to Get ItemPrice 30 and ShippingPrice 5.

Any Suggestions??

2

There are 2 best solutions below

4
On BEST ANSWER

This is a classical problem of default namespace. Your XML has default namespace declared at the root element :

xmlns="https://mws.amazonservices.com/Orders/2013-09-01"

All elements without prefix are considered in the above mentioned default namespace. To select element in namespace, you need to use XmlNamespaceManager:

var nsmgr = new XmlNamespaceManager(new NameTable());
//register mapping of prefix to namespace uri 
nsmgr.AddNamespace("d", "https://mws.amazonservices.com/Orders/2013-09-01");

string query = "/d:ListOrderItemsResponse/d:ListOrderItemsResult/d:OrderItems/d:OrderItem/d:ItemPrice/d:Amount";
XmlNode node = xd1.SelectSingleNode(query, nsmgr);
string itemPrice = node.InnerText;
0
On

With the second method, you can use the XmlElement Parent property, to get the name of the parent.

 XmlNodeList amounts = xml.GetElementsByTagName("Amount");
            foreach (XmlElement amount in amounts)
            {
                if (amount.ParentNode != null)
                {
                    if (amount.ParentNode.Name.Equals("ItemPrice"))
                    {
                        Console.WriteLine("Item Price"+amount.InnerText);
                    }
                    if (amount.ParentNode.Name.Equals("ShippingPrice"))
                    {
                        Console.WriteLine("Shipping Price" + amount.InnerText);

                    }
                }
            }

I hope this can help you.