Often, you want to parse an XML document using xpath and retrieve values, for example to read the DCR’s title field and set the metadata value with it. Here’s a quick code snippet to do that:

try {
 DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
 DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
 Document dcrDocument = documentBuilder.parse(new File(filePath));
 XPathFactory xPathfactory = XPathFactory.newInstance();
 XPath xPath = xPathfactory.newXPath();
 String titleXPathExpression = "/article/title";
 String title = (String)xPath.evaluate(titleXPathExpression, dcrDocument, XPathConstants.STRING);
 System.out.println("found DCR title " + title); CSExtendedAttribute[] extendedAttributes = {new CSExtendedAttribute("TeamSite/Metadata/Title", title)};
 cSSimpleFile.setExtendedAttributes(extendedAttributes);
} catch (Exception e) {
 Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "unable to set metadata title",e);
}

Leave a comment

Blog at WordPress.com.