Search code examples
c#xmldocument

Select list of node by innertext. Issue XmlDocument


I have following Xml

<Main>
         <Order Id="1262">
            <Product>
               <Name>Prod1</Name>
                   <Barcode>1234</Barcode>
                </Product>
                 <Product>
                   <Name>Prod1</Name>
                   <Barcode>1234</Barcode>
                </Product>
                <Product>
                     <Name>Prod2</Name>
                   <Barcode>2345</Barcode>
               </Product>

            </Order>

        <Order Id="1263">
               <Product>
               <Name>Prod1</Name>
                   <Barcode>1234</Barcode>
                </Product>
                 <Product>
                   <Name>Prod1</Name>
                   <Barcode>1234</Barcode>
                </Product>
                <Product>
                     <Name>Prod2</Name>
                   <Barcode>2345</Barcode>
               </Product>
                </Order>
</Main>


XmlDocument xml=new XmlDocument();
xml.Load(path);

Now I want to select only nodes whose barcode is 1234 from Node whose orderId=1263. My code is

 string OrderId="1262"
   string ReadedBarcode ="1234"

    XmlNode ONode = xml.SelectSingleNode("//Order[@Id='" + OrderId + "']");
     XmlNodeList BarCodeNodeList = ONode.SelectNodes("//Product/Barcode[text()='" + ReadedBarcode + "']");

But I dont know why all the nodes from document having innertext 1234 are getting selected. that means even node from <Order Id="1263"> this node is getting selected.

Any Solutions?


Solution

  • This should do it

            XmlDocument xml=new XmlDocument();
            xml.Load(path);
            string OrderId = "1262";
            string ReadedBarcode = "1234";
    
            XmlNodeList BarCodeNodeList = xml.SelectNodes("//Order[@Id='" + OrderId + "']"+"//Product/Barcode[text()='" + ReadedBarcode + "']");
    

    Also, your XML is invalid, it is missing some start tags, it should be

    <Main>
      <Order Id="1262">
        <Product>
        <Name>Prod1</Name>
        <Barcode>1234</Barcode>
        </Product>
        <Product>
          <Name>Prod1</Name>
          <Barcode>1234</Barcode>
        </Product>
        <Product>
          <Name>Prod2</Name>
          <Barcode>2345</Barcode>
        </Product>
    
      </Order>
    
      <Order Id="1263">
        <Product>
        <Name>Prod1</Name>
        <Barcode>1234</Barcode>
        </Product>
        <Product>
          <Name>Prod1</Name>
          <Barcode>1234</Barcode>
        </Product>
        <Product>
          <Name>Prod2</Name>
          <Barcode>2345</Barcode>
        </Product>
      </Order>
    </Main>