Mega Code Archive

 
Categories / Java / XML
 

XPath with JDOM

import java.io.File; import java.text.SimpleDateFormat; import java.util.Date; import org.jdom.Document; import org.jdom.Element; import org.jdom.Namespace; import org.jdom.input.SAXBuilder; import org.jdom.xpath.XPath; public class MainClass {   public static void main(String[] args) throws Exception {     Namespace NS_GUEST = Namespace.getNamespace("g", "uri:c:guest");     Namespace NS_SCHEDULE = Namespace.getNamespace("s", "uri:c:schedule");     SAXBuilder builder = new SAXBuilder();     Document document = builder.build(new File("tds_ns.xml"));     XPath xPath = XPath.newInstance("/s:schedule/s:show[@date=$date]/g:guest");     xPath.addNamespace(NS_SCHEDULE);     xPath.addNamespace(NS_GUEST);     String formattedDate = new SimpleDateFormat("MM.dd.yy").format(new Date(2006, 5, 14));     xPath.setVariable("date", formattedDate);     Element guest = (Element) xPath.selectSingleNode(document);     System.out.println(guest.getChildText("name", NS_GUEST));   } }