我正在使用带有 Ajax 的 Spring。通过 Ajax,我正在调用一个控制器方法,在该方法中我正在加载一个 xml 文件并对其进行解析。我想将解析的节点(对象)传递给 html 页面作为对 Ajax 调用的响应。
这是我的 Ajax 调用
$.ajax({
url: "query1",
type: "POST",
//dataType: "xml",
success: function(data) {
alert("in jax response");
alert("DATA" + data);
// parseXml(data);
}
});
这是我的控制器方法
@RequestMapping(value = "/query1", method = RequestMethod.POST)
public @ResponseBody Node executeQuery1(ModelMap model) throws ParserConfigurationException, SAXException,IOException, XPathExpressionException {
// Standard of reading a XML file
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder;
Document doc = null;
XPathExpression expr = null;
builder = factory.newDocumentBuilder();
String filepath = "C:\\test.xml";
System.out.println("PATH: " + filepath);
doc = builder.parse(filepath);
// Create a XPathFactory
XPathFactory xFactory = XPathFactory.newInstance();
// Create a XPath object
XPath xpath = xFactory.newXPath();
// Compile the XPath expression
expr = xpath.compile("//person[@id=1]");
// Run the query and get a nodeset
Object result = expr.evaluate(doc, XPathConstants.NODE);
// Cast the result to a DOM NodeList
Node personNode = (Node) result;
model.addAttribute("xmlnode", personNode);
System.out.println("model set. going to return");
return personNode;
}
如果我返回一个字符串而不是节点,我会收到警报弹出窗口。但是在返回节点对象时它失败了。
另外我想在 Javascript 中进一步解析这个节点。所以请让我知道最好的方法。我应该将节点转换为 XML 字符串并返回 XML 字符串吗?