我正在尝试使用Xpath解析xml文件。下面是我的代码。
File inputFile = new File("package.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder;
dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(inputFile);
doc.getDocumentElement().normalize();
XPath xPath = XPathFactory.newInstance().newXPath();
String expression = "/package/group/table";
NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(doc, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
Node nNode = nodeList.item(i);
System.out.println("\nCurrent Element :" + nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
System.out.println("Table name : " + eElement.getAttribute("name"));
System.out.println("Default : " + eElement.getAttribute("default"));
System.out.println("ID : " + eElement.getAttribute("id"));
}
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
用于处理的XML文件如下:
<?xml version="1.0" encoding="UTF-8"?>
<package name="FBNK.SECTOR">
<group name="FBNK.SECTOR">
<table name="FBNK.SEC" default="FBNK.SECTOR" id="SECTOR.CODE">
<column name="DESCRIPTION" size="35" type="A" position="1" singlemulti="M" subvalue="NO" mvgroupno="1" descriptor="C" />
</table>
<table name="FBNK.SECTOR$HIS" default="FBNK.SECTOR$HIS" id="SECTOR.CODE">
<column name="AUDIT.DATE.TIME" size="50" position="17" singlemulti="S" subvalue="NO" descriptor="C" />
</table>
</group>
<group name="funds.transfer">
<table name="FBNK.FUNDS.TRANSFER" default="FBNK.FUNDS.TRANSFER" id="REF.NO">
<column name="AC.CHG.REQ.ID" size="35" type="A" position="147" singlemulti="S" subvalue="NO" descriptor="C" />
<column name="TREASURY.RATE" size="16" type="R" position="16" singlemulti="S" subvalue="NO" descriptor="C" />
</table>
</group>
</package>
目前我的问题是我只得到 / package / group / table下的表达式。你能帮我拿到同样的包** / group / table / column **使用Xpath?提前谢谢..
答案 0 :(得分:1)
以下是检索当前处理的表的列的方法(引用为nNode
):
NodeList columnList = (NodeList) xPath.compile("column").evaluate(nNode, XPathConstants.NODESET);