user3387482 user3387482 - 1 month ago 17
Java Question

How to Fetch Value from XML document and store it in a variable using Selenium Java

Am new to Automation and am using Selenium with Java.

I have a Problem where i need to go through an XML file find a Node and read the value in that node. And i need to compare the value with the Input String.

Can someone please help me how to read the xml file and fetch the value from the xml and store it in a variable.

<?xml version="1.0"?>
-<cXML timestamp="2017-06-15T18:26:00.271+05:30" payloadID="7500610099-0-PORQ" version="1.2.011">
-<Header>
+<From>
+<To>
+<Sender>
</Header>
-<Request deploymentMode="test">
-<OrderRequest>
+<OrderRequestHeader type="new" orderType="release" orderDate="2017-06-15" orderID="7500610099-0">
+<ItemOut requestedDeliveryDate="2017-06-02" quantity="1" lineNumber="5">
+<ItemOut requestedDeliveryDate="2017-06-02" quantity="1" lineNumber="5">
+<ItemOut requestedDeliveryDate="2017-05-23" quantity="1" lineNumber="1">
+<ItemOut requestedDeliveryDate="2017-05-23" quantity="1" lineNumber="2">
-<ItemOut requestedDeliveryDate="2017-05-23" quantity="9" lineNumber="3">
-<ItemID>
<SupplierPartID>1*VP470</SupplierPartID>
</ItemID>


I Need to Read the Value inside the node
<SupplierPartID>


Thanks,
Satish D

Answer Source

We can use Java inbuilt libraries to create a regex pattern and search for that in the String(data in the file). The below code might give you some idea.

public static void main(String[] args) throws FileNotFoundException 
{
    //Change the path for the file
    String content = new Scanner(new File("/home/santhoshkumar/Desktop/sample.xml")).useDelimiter("\\Z").next();

    //System.out.println(content);

    Pattern pattern = Pattern.compile("<SupplierPartID>(.*)</SupplierPartID>");    
    Matcher matcher = pattern.matcher(content);  

    while (matcher.find()) 
    {    
        System.out.println(matcher.group(1));    

    }    
}

Hope this helps you. Thanks