是自动化的新手,我正在使用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>
谢谢, Satish D
答案 0 :(得分:0)
我们可以使用Java内置库来创建正则表达式模式,并在String中搜索该模式(文件中的数据)。以下代码可能会给你一些想法。
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));
}
}
希望这会对你有所帮助。感谢
答案 1 :(得分: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());
}