0

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

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”操作分配给变量并将其作为返回(某物)返回是一个好主意。

非常感谢

干杯!!

哈维

4

3 回答 3

1

这些类工作正常,我可以在控制台中看到结果,但我想将“process.query()”的结果分配给一个变量,以便在此过程之后使用它。

因此,您必须将函数 vom "void" 的返回值类型更改为 fe "org.w3c.dom.Document",并且您必须更改函数以使其返回有效的 xml 文档

于 2013-10-16T13:35:19.930 回答
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());
        }
  }
于 2013-10-16T13:45:06.757 回答
0

将您 System.out.print(nodes.item(i).getNodeValue());的替换为 System.out.print(nodes.item(0).getFirstChild().getNodeValue());与此同时,您还需要检查 null 以了解getFirstChild您的标签何时是这样的<a/>

于 2013-10-16T13:35:15.553 回答