HashMaps-WebElements

问题描述 投票:0回答:2

有人可以协助我尝试使用HASHMAP达成以下目标吗?我不是使用HashMaps的专家

WebElement xmlResponse = iframeElements9.findElement(By.name("currentContactInfo.messageRecord.resMsg"));
WebElement xmlRequest = iframeElements9.findElement(By.name("currentContactInfo.messageRecord.reqMsg"));
WebElement[] listOfElements = {xmlRequest,xmlResponse};

FileHandlers outputToTextFile = new FileHandlers();
ConvertOutputToXML convert = new ConvertOutputToXML();

String textAreaValue=null;
String FileName =  null;
org.w3c.dom.Document xmlOutput = null;
//iterating through the Array, this works fine but would like to achieve the same using hashmap
for (int j=0;j<listOfElements.length; j++){
   textAreaValue = listOfElements[j].getText(); //using the Hashmap I would like to invoke getText
   FileName = outputToTextFile.writeToFile(textAreaValue);// i then write this output to a file
   convert.ReadTextFile(FileName);
   xmlOutput = (org.w3c.dom.Document) convert.convertToXML(textAreaValue);
}

//This is the equivalent trying with a Hashmap
HashMap<String, WebElement> XMLData = new HashMap<>();
XMLData.put("reqMsg",xmlRequest);
XMLData.put("resMsg",xmlResponse);
for (int i = 0; i < XMLData.size(); i++)
{
 System.out.println(XMLData.get(i).getText());  //null pointer exception is what I get
}

理想情况下,我想使用键“ reqMsg”或“ resMsg”将文本区域的输出写入文件,每个消息在其自己的文件中,使用Array都能正常工作,但只需要键即可。

java selenium-webdriver
2个回答
0
投票

要从HashMap中获取值,应使用get()方法通过键进行访问。要访问这些元素,您应该执行以下操作:

XMLData.get("your_key")

您的情况是这样的:

HashMap<String, WebElement> XMLData = new HashMap<>();
XMLData.put("reqMsg",xmlRequest);
XMLData.put("resMsg",xmlResponse);

 System.out.println(XMLData.get("reqMsg").getText()); 
 System.out.println(XMLData.get("resMsg").getText()); 

然后您可以将数据写入文件。


0
投票

非常感谢A.Wolf,感谢您的快速回复

© www.soinside.com 2019 - 2024. All rights reserved.