gpt4 book ai didi

java - 如何获得 "For"操作的结果?

转载 作者:行者123 更新时间:2023-12-02 06:38:26 25 4
gpt4 key购买 nike

我想做的是获取从以下类生成的结果:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com