user1926152
user1926152

Reputation: 235

Extracting the particular part of an XML

I have an XML in a string variable i want to check if this xml content contains

<xml>
<message display='yes'>
....

or

<xml>
<xdp:xdp>
...

is it possible?

Upvotes: 1

Views: 110

Answers (2)

Ivan Golović
Ivan Golović

Reputation: 8832

Here is how you can check for it:

        string example = @"<xml>
            <message display='yes'></message>
            </xml>";

        XDocument doc = XDocument.Parse(example);
        if (doc.Element("xml").Element("message") != null)
        {
            // node "message" exists within node "xml" which is located at the root of the document
        }

You can use XDocument class to check for existence of any node at any location in the hierarchy of an XML document. You can load contents from string or file easily.

Upvotes: 1

Amit
Amit

Reputation: 7035

An example below

<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>

    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");

Upvotes: 0

Related Questions