I extended my demo project further. See
The Application Under Test Sample now has 3 rows:
Please note: The 1st row contains 1 link to XML. The 2nd row contains no link to XML. The 3rd row contains 2 links to XML files.
I added a Test Case TC3. This test case scans the target HTML for <a> elements to XML file. I took it into account that a <tr> element may contain zero, 1, 2 or more <a> elements to XML.
WebUI.openBrowser('')
WebUI.navigateToUrl('https://kazurayam.github.io/SavingAnXmlFileRatherThanDisplayingIt/')
WebUI.verifyElementPresent(findTestObject('Page_Sample/div_resultDiv'), 10)
// prepare output directory
Path projectdir = Paths.get(RunConfiguration.getProjectDir())
Path outputdir = projectdir.resolve("tmp")
// grasp <tr> elements
List<WebElement> trElements = WebUI.findWebElements(
new TestObject().addProperty("xpath", ConditionType.EQUALS,
"//div[@id='resultDiv']/table/tbody/tr"), 10)
for (int i = 0; i < trElements.size(); i++) {
// grasp <a> elements to XML
List<WebElement> anchorElements = WebUI.findWebElements(
new TestObject().addProperty("xpath", ConditionType.EQUALS,
"//div[@id='resultDiv']/table/tbody/tr[${i+1}]/td[6]/a"), 10)
for (int j = 0; j < anchorElements.size(); j++) {
String href = anchorElements.get(j).getAttribute("href")
// determin the file location
Path outfile = outputdir.resolve("sample(${i},${j}).xml")
WebUI.comment("(${i},${j}) href=${href} outfile=${outfile.toString()}")
// download XML and save it into file
WebUI.callTestCase(findTestCase("modules/DownloadXML"),
["href":href, "outfile": outfile.toString()],
FailureHandling.OPTIONAL)
}
}
WebUI.closeBrowser()
The TC3 calls another test case named modules/DownloadXML
:
/**
* @param href (java.lang.String) URL of XML file to download
* @param outfile (java.lang.String) path of the file into which the XML is saved
*/
Objects.requireNonNull(href)
Objects.requireNonNull(outfile)
// Create a new GET object using builder
def builder = new RestRequestObjectBuilder()
def requestObject =
builder.withRestRequestMethod("GET")
.withRestUrl(href) // here we specify the URL found in the web site
.build()
// Send a request
def response = WS.sendRequest(requestObject)
// Verify if the response from the URL returns the 200 status code'
WS.verifyResponseStatusCode(response, 200)
// Get the content string
def content = response.getResponseBodyContent()
Path file = Paths.get(outfile)
// prepare output directory
Files.createDirectories(file.getParent())
// save XML into file
file.toFile().write(content))
By executing TC3, I got a few xml files created in the tmp directory under the project dir.
:tmp [master]$ tree
.
├── sample(0,0).xml
├── sample(2,0).xml
└── sample(2,1).xml
0 directories, 3 files
The mission is accomplished, isn’t it?