001 /* 002 * Common usable utilities 003 * 004 * Copyright (c) 2006 Petr Hadraba <hadrabap@gmail.com> 005 * 006 * Author: Petr Hadraba 007 * 008 * -- 009 * 010 * XML Utilities 011 */ 012 013 package global.sandbox.xmlutilities.demo; 014 015 import global.sandbox.xmlutilities.NamespaceContextImpl; 016 import global.sandbox.xmlutilities.XmlTools; 017 import global.sandbox.xmlutilities.XmlUtilitiesException; 018 import javax.xml.namespace.NamespaceContext; 019 import org.w3c.dom.Attr; 020 import org.w3c.dom.Element; 021 import org.w3c.dom.Node; 022 023 public class XPathEvaluation { 024 025 final static NamespaceContext NAMESPACES; 026 027 static { 028 final NamespaceContextImpl nspaces = NamespaceContextImpl.namespaceContextWithDefaults(); 029 nspaces.addNamespace( 030 "ns", 031 "http://hadrabap.googlepages.com/projects/xmlutilities/demo"); 032 033 NAMESPACES = nspaces; 034 } 035 036 public static Attr loadAttribute(Element rootNode, String xPathQuery) throws XPathEvaluationException { 037 Node node; 038 try { 039 node = XmlTools.getFirstNodeForXPath( 040 xPathQuery, 041 rootNode, 042 NAMESPACES); 043 } catch (XmlUtilitiesException ex) { 044 throw new XPathEvaluationException(ex); 045 } 046 047 if (node == null) { 048 return null; 049 } 050 051 if (node.getNodeType() == Node.ATTRIBUTE_NODE) { 052 return (Attr) node; 053 } else { 054 throw new XPathEvaluationException(String.format("Resulting node is not Attr, got %d.", node.getNodeType())); 055 } 056 } 057 058 public static Attr loadAttribute12(Element rootNode, String xPathQuery) throws XmlUtilitiesException { 059 return XmlTools.getFirstNodeForXPath( 060 xPathQuery, 061 rootNode, 062 NAMESPACES, 063 Attr.class); 064 } 065 066 public static class XPathEvaluationException extends Exception { 067 068 private static final long serialVersionUID = 1L; 069 070 public XPathEvaluationException(String message) { 071 super(message); 072 } 073 074 public XPathEvaluationException(Throwable cause) { 075 super(cause); 076 } 077 078 } 079 080 }