作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想做的是获取从以下类生成的结果:
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”操作分配给变量并将其作为返回(某物)返回是一个好主意。
非常感谢
干杯!!
哈维
最佳答案
首先,您需要从 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());
}
}
关于java - 如何获得 "For"操作的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19404800/
我是一名优秀的程序员,十分优秀!