我需要读取xml文档内容并使用xpath
读取键值对document.xml中
<?xml version="1.0" encoding="UTF-8"?>
<Disposition-Config>
<LOB>
<lob_pair key = "0" value = "N/A"/>
</LOB>
<SourceCode>
<sourcecode_pair key = "0" value = "N/A"/>
</SourceCode>
<TerminationCode>
<terminationcode_pair key = "0" value = "N/A"/>
</TerminationCode>
</Disposition-Config>
jsp scriplet
<%
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
try {
out.println(request.getRealPath("/WEB-INF/disposition.xml"));
Document doc = db.parse(new File(request.getRealPath("/WEB-INF/document.xml")));
out.println(doc);
String lobExpression = "/Disposition-Config/LOB/lob_pair";
String sourceCodeExpression = "/Disposition-Config/SourceCode/sourcecode_pair";
String terminationCodeExpression = "/Disposition-Config/TerminationCode/terminationcode_pair";
CMETabReader cmeTabReader = new CMETabReader();
/* class to retrieve key value from xml */
cmeTabReader.getDispositionValues(doc, lobExpression);
} catch(Exception e) {
out.print(e);
e.printStackTrace();
}
%>
但是当我尝试使用
打印xml文档时<% out.println(doc) %>
它的印刷品如
[#document: null]
任何建议???
答案 0 :(得分:1)
public static void main(String[] arg){
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder;
try {
builder = factory.newDocumentBuilder();
Document doc = builder.parse("book.xml");
XPathFactory xfactory = XPathFactory.newInstance();
XPath xpath = xfactory.newXPath();
XPathExpression expr = xpath.compile("//lob_pair//@value");
String result = (String)expr.evaluate(doc, XPathConstants.STRING);
System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}
}
您可以使用此在线解析器http://chris.photobooks.com/xml/default.htm
测试您的xpath表达式答案 1 :(得分:0)