我想要做的是获得从以下类生成的resut:
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()”的rsult分配给一个变量,以便在此过程之后使用它。
我不知道是否可能,或者即使将“for”操作分配给变量并将其作为返回(某些东西)返回是一个好主意。
非常感谢
干杯!!
哈维
答案 0 :(得分:1)
这些类工作正常,我可以在控制台中看到结果,但我想将“process.query()”的rsult分配给一个变量,以便在此过程之后使用它。
因此,您必须将函数vom“void”的返回值类型更改为f.e. “org.w3c.dom.Document”你必须改变你的功能,以便它返回一个有效的xml文件
答案 1 :(得分:1)
首先,您需要从query()
方法返回结果:
public NodeList query() throws ParserConfigurationException,
SAXException,IOException,XPathExpressionException {
...
// Cast the result to a DOM NodeList
NodeList nodes = (NodeList) result;
return nodes;
}
然后,您可以将结果添加到数组中以便稍后处理:
public static void main(String[] args) throws XPathExpressionException,
ParserConfigurationException, SAXException, IOException {
String Queries[]={
"//Employees/Employee/Firstname/City/@value",
"//Employees/Employee/Firstname/Lastname/@value"
};
List<NodeList> results = new ArrayList<NodeList>();
for (int x =0; x < Queries.length; x++){
String query = Queries[x];
QueryXML process = new QueryXML(query);
results.add(process.query());
}
}
答案 2 :(得分:0)
将您的System.out.print(nodes.item(i).getNodeValue());
替换为System.out.print(nodes.item(0).getFirstChild().getNodeValue());
同时,如果您的代码是getFirstChild
<a/>
的空值