我试图从同一个类中不同方法的方法中读取返回的ArrayList。我的阅读方法看起来像
public static ArrayList<String> readXml(String[] args) throws Exception {
// String baseServer;
// String FirstName;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
//Parsing of Book.xml is done here
Document document = builder.parse(new File("C://Javaseleniumworld/Book.xml"));
document.getDocumentElement().normalize();
ArrayList<String> testData = new ArrayList<>();
// double[] dataList = new double[100];
NodeList node = document.getElementsByTagName("TestData");
// NodeList nodeList = document.getDocumentElement().getChildNodes();
System.out.println("TestData Details");
System.out.println("________________________________________________");
for (int i = 0; i < node.getLength(); i++) {
//We have encountered an <employee> tag.
Node currentNode = node.item(i);
if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) currentNode;
NodeList blocksserverElementList = element.getElementsByTagName("server");
// NodeList blocksServerElementList = element.getElementsByTagName("server");
Element blocksServer = (Element) blocksserverElementList.item(0);
// NodeList blocksServer1 = blocksServer.getChildNodes();
String baseServer = ((Node) blocksServer).getNodeValue();
System.out.println("Mail Servername:" + blocksServer);
testData.add(baseServer);
NodeList firstNameElementList = element.getElementsByTagName("firstname");
Element UName = (Element) firstNameElementList.item(0);
// NodeList UName = UName.getChildNodes();
String FirstName1 = ((Node) UName).getNodeValue();
System.out.println("First Name:" + FirstName1);
testData.add(FirstName1);
// return testData;
}
}
return testData;
}
现在我想用另一种方法
读取返回的testDataArrayList returnedData = StartCaseJava.readXml(new String [1]);
我尝试打印returnedData来检查内容,但没有显示任何内容。
答案 0 :(得分:1)
public void printStringList(List<String> list){
for(String item : list){
System.out.println(item);
}
}
答案 1 :(得分:0)
You can iterate over the list in java as below:
ArrayList<String> sampleList = new ArrayList<String>();
sampleList.add("Element A");
sampleList.add("Element B");
sampleList.add("Element C");
// traditional way
System.out.println("Traditional : ");
for (int i = 0; i < sampleList.size(); i++) {
System.out.println(sampleList.get(i));
}
// for each
System.out.println("For each : ");
for (String element : sampleList) {
System.out.println(element);
}
// functional java 8 way
System.out.println("Functional looping : ");
sampleList.stream().forEach((element) -> {
System.out.println(element);
});