我想要做的是获得从以下类生成的结果:
public class QueryXML {
public String query;
public QueryXML(String query){
this.query=query;
}
public void query() throws ParserConfigurationException, SAXException,IOException,XPathExpressionException {
// Standard of reading an XML file
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder;
Document doc = null;
XPathExpression expr = null;
builder = factory.newDocumentBuilder();
doc = builder.parse("C:data.xml");
// create an XPathFactory
XPathFactory xFactory = XPathFactory.newInstance();
// create an XPath object
XPath xpath = xFactory.newXPath();
// Compile the XPath expression
expr = xpath.compile(query);
// Run the query and get a nodeset
Object result = expr.evaluate(doc, XPathConstants.NODESET);
// Cast the result to a DOM NodeList
NodeList nodes = (NodeList) result;
for (int i=0; i<nodes.getLength();i++){
System.out.print(nodes.item(i).getNodeValue());
}
}
}
这个类是从另一个类中调用的:
public class FindUser {
public static void main(String[] args) throws XPathExpressionException, ParserConfigurationException, SAXException, IOException {
String Queries[]={"//Employees/Employee/Firstname/City/@value", "//Employees/Employee/Firstname/Lastname/@value"};
for (int x =0; x < Queries.length; x++){
String query = Queries[x];
QueryXML process = new QueryXML(query);
process.query();
}
}
}
这些类工作正常,我可以在控制台中看到结果,但我想将“process.query()”的结果分配给一个变量,以便在此过程之后使用它。
我不知道是否有可能,或者即使将“for”操作分配给变量并将其作为返回(某物)返回是一个好主意。
非常感谢
干杯!!
哈维