2017-06-16 16 views
1

自動化新增功能,並且使用Selenium和Java。如何從XML文檔提取值並使用Selenium將其存儲在變量中Java

我有一個問題,我需要通過一個XML文件找到一個節點並讀取該節點中的值。我需要將該值與輸入字符串進行比較。

有人可以幫助我如何讀取xml文件並從xml中獲取值並將其存儲在變量中。

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

我需要閱讀價值的節點內<SupplierPartID>

感謝, 薩蒂什南比亞d

+0

這是一個單獨的XML文件,你會通過普通的Java從本地讀取它? –

+0

@santhoshkumar - 是的這是一個單獨的文件,我會從共享位置讀取它。但現在讓我們假設我在桌面上有這個文件並從本地讀取它。 – user3387482

+0

你爲什麼要使用硒?您可以使用xml解析器或Xpath來解析xml以僅選擇該元素 – metar

回答

0

我們可以使用Java內置庫,創建一個正則表達式模式和搜索,在字符串(數據在文件中)。下面的代碼可能會給你一些想法。

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

    }  
} 

希望這可以幫助你。謝謝

+0

下面的代碼像寶石一樣工作 – user3387482

0

下面的代碼像寶石一樣工作。

import javax.xml.parsers.DocumentBuilder; 
import javax.xml.parsers.DocumentBuilderFactory; 
import org.w3c.dom.Document; 
import org.w3c.dom.Element; 
import org.w3c.dom.Node; 
import org.w3c.dom.NodeList; 


DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
      DocumentBuilder builder = factory.newDocumentBuilder();     

      //Parsing of xml is done here 
      Document doc = builder.parse(new File("C:\\Users\\User_Name\\Documents\\My Received Files\\PDSL_ABM.xml")); 

      //Here we get the root element of XML and print out 
      doc.getDocumentElement().normalize(); 
      System.out.println ("Root element of the doc is " + doc.getDocumentElement().getNodeName()); 

      NodeList list = doc.getElementsByTagName("SupplierPartID"); 
      int totalSupplierPartID =list.getLength(); 
      System.out.println("Total no of SupplierPartID : " + totalSupplierPartID); 



      //Traversing all the elements from the list and printing out its data 
      for (int i = 0; i < list.getLength(); i++) { 

      //Getting one node from the list. 
      Node childNode = list.item(i); 
      System.out.println("SupplierPartID : " + childNode.getTextContent()); 
      } 
相關問題