Reputation: 623
I am trying to parse an xml file using Xpath. Below is my piece of code for it.
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();
}
The XML file use for processing is below :
<?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>
Currently my problem is i am getting only the expression found under /package/group/table. Can u pls help me to get the same package**/group/table/column** how to get using Xpath ? Thanks in advance..
Upvotes: 1
Views: 65
Reputation: 24812
Here's how to retrieve the columns of the currently handled table (referenced as nNode
) :
NodeList columnList = (NodeList) xPath.compile("column").evaluate(nNode, XPathConstants.NODESET);
Upvotes: 1