public int getRecordCount () { Map<String,String> uris = new HashMap<String,String>(); uris.put( "ddsws", "http://www.dlese.org/Metadata/ddsws" ); uris.put( "groups", "http://www.dlese.org/Metadata/groups/" ); uris.put( "adn", "http://adn.dlese.org" ); uris.put( "annotation", "http://www.dlese.org/Metadata/annotation" ); XPath xpath = DocumentHelper.createXPath( "//ddsws:results/ddsws:record" ); xpath.setNamespaceURIs( uris ); List recordNodes = xpath.selectNodes(this.document); return recordNodes.size(); }
private Element getTagElement (String _tag, String _namespacePrefix, String _namespaceURI ) { Element tagElement = null; // caller is responsible for handling null try { // TODO this isn't complete, as we can have any arbitrary tag and values for them infinitely deep XPath xpath = DocumentHelper.createXPath( "//" + ( _namespacePrefix != null ? _namespacePrefix + ":" : "" ) + _tag.trim() ); SimpleNamespaceContext ns = new SimpleNamespaceContext(); ns.addNamespace( _namespacePrefix, _namespaceURI ); xpath.setNamespaceContext(ns); tagElement = ((Element)xpath.selectSingleNode(this.infoxmlDoc)); } catch ( Exception e ) { e.printStackTrace(); } return tagElement; }
@Test public void shouldBuildDocumentFromSetOfXPaths() throws XPathExpressionException, IOException { Map<String, Object> xmlProperties = fixtureAccessor.getXmlProperties(); Document builtDocument = new XmlBuilder(namespaceContext) .putAll(xmlProperties.keySet()) .build(DocumentHelper.createDocument()); for (Entry<String, Object> xpathToValuePair : xmlProperties.entrySet()) { XPath xpath = builtDocument.createXPath(xpathToValuePair.getKey()); if (null != namespaceContext) { xpath.setNamespaceContext(new SimpleNamespaceContextWrapper(namespaceContext)); } assertThat(xpath.evaluate(builtDocument)).isNotNull(); } assertThat(xmlToString(builtDocument)).isEqualTo(fixtureAccessor.getPutXml()); }
@Test public void shouldBuildDocumentFromSetOfXPathsAndSetValues() throws XPathExpressionException, IOException { Map<String, Object> xmlProperties = fixtureAccessor.getXmlProperties(); Document builtDocument = new XmlBuilder(namespaceContext) .putAll(xmlProperties) .build(DocumentHelper.createDocument()); for (Entry<String, Object> xpathToValuePair : xmlProperties.entrySet()) { XPath xpath = builtDocument.createXPath(xpathToValuePair.getKey()); if (null != namespaceContext) { xpath.setNamespaceContext(new SimpleNamespaceContextWrapper(namespaceContext)); } assertThat(xpath.selectSingleNode(builtDocument).getText()).isEqualTo(xpathToValuePair.getValue()); } assertThat(xmlToString(builtDocument)).isEqualTo(fixtureAccessor.getPutValueXml()); }
public Element getElement( String xpathExpr ) throws XMLException { XPath xpath = createXPath( xpathExpr ); Object evaluated = xpath.selectSingleNode( document ); if ( evaluated == null ) { return null; } if ( evaluated instanceof Element ) { return (Element) evaluated; } else { // Unknown evaluated type. throw new XMLException( ".getElement( Expr: " + xpathExpr + " ) resulted in non-Element type -> (" + evaluated.getClass().getName() + ") " + evaluated ); } }
public String getElementText( Node context, String xpathExpr ) throws XMLException { XPath xpath = createXPath( xpathExpr ); Object evaluated = xpath.selectSingleNode( context ); if ( evaluated == null ) { return null; } if ( evaluated instanceof Element ) { Element evalElem = (Element) evaluated; return evalElem.getTextTrim(); } else { // Unknown evaluated type. throw new XMLException( ".getElementText( Node, Expr: " + xpathExpr + " ) resulted in non-Element type -> (" + evaluated.getClass().getName() + ") " + evaluated ); } }
public String getElementText( String xpathExpr ) throws XMLException { XPath xpath = createXPath( xpathExpr ); Object evaluated = xpath.selectSingleNode( document ); if ( evaluated == null ) { return null; } if ( evaluated instanceof Element ) { Element evalElem = (Element) evaluated; return evalElem.getTextTrim(); } else { // Unknown evaluated type. throw new XMLException( ".getElementText( Expr: " + xpathExpr + " ) resulted in non-Element type -> (" + evaluated.getClass().getName() + ") " + evaluated ); } }
public void getXmlUser(Document doc, Map<String, String> userColumn) { // 根据xpath方式得到所要得到xml文档的具体对象,根据分析解析xml文档可知,xml文档中含有前缀名 Map<String, String> map = new HashMap<String, String>(); map.put("c", "collection"); // 根据xml文档,//c:Table 即为得到的文档对象 XPath path = doc.createXPath("//c:Users"); path.setNamespaceURIs(map); List<Element> list = path.selectNodes(doc); // 得到tables对象,该对象是该pdm文件中所有表的集合 for (Element element : list) { for (Iterator<Element> iter = element.elementIterator("User"); iter .hasNext();) { Element userElement = iter.next(); Attribute attribute = userElement.attribute("Id"); userColumn.put(attribute.getText(), userElement.elementText("Code")); // setUserlist(userElement.elementText("Code")); } } }
public boolean isMysql(Document doc) { // 根据xpath方式得到所要得到xml文档的具体对象,根据分析解析xml文档可知,xml文档中含有前缀名 Map<String, String> map = new HashMap<String, String>(); map.put("c", "collection"); // 根据xml文档,//c:Table 即为得到的文档对象 XPath path = doc.createXPath("//c:DBMS"); path.setNamespaceURIs(map); List<Element> list = path.selectNodes(doc); // 得到tables对象,该对象是该pdm文件中所有表的集合 for (Element element : list) { for (Iterator<Element> iter = element.elementIterator("Shortcut"); iter .hasNext();) { Element userElement = iter.next(); String s = userElement.elementText("Code").toUpperCase(); if (s.substring(0, 5).equals("MYSQL")) { logger.debug(s); return true; } else if (s.substring(0, 6).equals("ORACLE")) { logger.debug(s); return false; } } } return false; }
/** * Extracts the value of the supplied attribute * * @param element * element with attribute in question * @param attributeName * name of the attribute in question * @param failIfNotFound * determines if exception should be thrown if attribute is not * found * @return value of the attribute in question, null if not found and * failIfNotFound is set to false * @throws GenericArtifactParsingException * exception thrown is attribute is missing and failIfNotFound * is set to true */ public static String getAttributeValue(Element element, String attributeName, boolean failIfNotFound) throws GenericArtifactParsingException { XPath xpath = new DefaultXPath("@" + attributeName); xpath.setNamespaceURIs(ccfNamespaceMap); Node attributeNode = xpath.selectSingleNode(element); if (attributeNode == null) { if (failIfNotFound) { throw new GenericArtifactParsingException("Missing attribute: " + attributeName + " in element " + element.getName()); } else { return null; } } else { return attributeNode.getText(); } }
private void convertTableSettings(final Document doc) { XPath xpathSelector = DocumentHelper.createXPath("/settings/columns/column"); List<?> results = xpathSelector.selectNodes(doc); List<String> tableColumnNames = new ArrayList<String>(); List<String> tableColumnVisible = new ArrayList<String>(); for (Iterator<?> iter = results.iterator(); iter.hasNext();) { Element element = (Element) iter.next(); Attribute name = element.attribute("name"); Attribute visible = element.attribute("visible"); tableColumnNames.add(name.getText()); if (visible.getText().equals("true")) { tableColumnVisible.add(name.getText()); } } String mode = convertFlag(doc); writeTableSettings(doc, mode, tableColumnNames, tableColumnVisible); }
private String convertFlag(final Document doc) { XPath flagSelector = DocumentHelper.createXPath("/settings/flags/flag"); List<?> flagResults = flagSelector.selectNodes(doc); boolean text = false; boolean window = false; for (Iterator<?> iter = flagResults.iterator(); iter.hasNext();) { Element element = (Element) iter.next(); Attribute key = element.attribute("key"); Attribute visible = element.attribute("enabled"); if (key.getText().equals("FLAG_AUTO_RESIZE_COLUMNS_TEXT")) { text = visible.getText().equals("true"); element.detach(); } if (key.getText().equals("FLAG_AUTO_RESIZE_COLUMNS_WINDOW")) { window = visible.getText().equals("true"); element.detach(); } } if (text) { return "TEXT"; } if (window) { return "WINDOW"; } return "NONE"; }
/** Get an XPath version of the given dotted path. A dotted path * foo.bar.baz corresponds to the XML node <foo><bar><baz> * </baz></bar></foo> * * Implementation note: If needed, this could be optimized by keeping a * HashMap cache of the XPaths, since they don't change. * * @param path A dotted path * @return An XPath that matches the dotted path equivalent, using * "dk:" as namespace prefix for all but the first element. */ private XPath getXPath(String path) { String[] pathParts = path.split("\\."); StringBuilder result = new StringBuilder(); result.append("/"); result.append(pathParts[0]); for (int i = 1; i < pathParts.length; i++) { result.append("/dk:"); result.append(pathParts[i]); } XPath xpath = xmlDoc.createXPath(result.toString()); Namespace nameSpace = xmlDoc.getRootElement().getNamespace(); Map<String, String> namespaceURIs = new HashMap<String, String>(1); namespaceURIs.put("dk", nameSpace.getURI()); xpath.setNamespaceURIs(namespaceURIs); return xpath; }
@SuppressWarnings("unchecked") private boolean applyXPath() { try{ XPath xpath = data.document.createXPath(data.PathValue); if(meta.isNamespaceAware()) { xpath = data.document.createXPath(addNSPrefix(data.PathValue, data.PathValue)); xpath.setNamespaceURIs(data.NAMESPACE); } // get nodes list data.an = (List<AbstractNode>) xpath.selectNodes(data.document); data.nodesize=data.an.size(); data.nodenr=0; }catch (Exception e) { log.logError(toString(),Messages.getString("GetXMLData.Log.ErrorApplyXPath",e.getMessage())); return false; } return true; }
@SuppressWarnings("unchecked") private boolean applyXPath() { try{ XPath xpath = data.document.createXPath(data.PathValue); if(meta.isNamespaceAware()) { xpath = data.document.createXPath(addNSPrefix(data.PathValue, data.PathValue)); xpath.setNamespaceURIs(data.NAMESPACE); } // get nodes list data.an = (List<AbstractNode>) xpath.selectNodes(data.document); data.nodesize=data.an.size(); data.nodenr=0; }catch (Exception e) { logError(BaseMessages.getString(PKG, "GetXMLData.Log.ErrorApplyXPath",e.getMessage())); return false; } return true; }
@SuppressWarnings( "unchecked" ) private boolean applyXPath() { try { XPath xpath = data.document.createXPath( data.PathValue ); if ( meta.isNamespaceAware() ) { xpath = data.document.createXPath( addNSPrefix( data.PathValue, data.PathValue ) ); xpath.setNamespaceURIs( data.NAMESPACE ); } // get nodes list data.an = xpath.selectNodes( data.document ); data.nodesize = data.an.size(); data.nodenr = 0; } catch ( Exception e ) { logError( BaseMessages.getString( PKG, "GetXMLData.Log.ErrorApplyXPath", e.getMessage() ) ); return false; } return true; }
public String getCollectionKeyFromDDS( String _collectionName ) { String collectionKey = null; // make the call to DDS and get ListCollections try { URLConnection connection = new URL ("http://www.dlese.org/dds/services/ddsws1-1?verb=ListCollections" ).openConnection(); connection.setDoOutput( true ); connection.setDoInput(true); ((HttpURLConnection)connection).setRequestMethod("GET"); Map<String,String> uris = new HashMap<String,String>(); uris.put( "ddsws", "http://www.dlese.org/Metadata/ddsws" ); uris.put( "ddswsnews", "http://www.dlese.org/Metadata/ddswsnews" ); uris.put( "groups", "http://www.dlese.org/Metadata/groups/" ); uris.put( "adn", "http://adn.dlese.org" ); uris.put( "annotation", "http://www.dlese.org/Metadata/annotation" ); XPath xpath = DocumentHelper.createXPath( "//collections/collection[vocabEntry=\"" + _collectionName + "\"]/searchKey/text()" ); xpath.setNamespaceURIs( uris ); SAXReader xmlReader = new SAXReader(); this.document = xmlReader.read(connection.getInputStream()); Text t = ((Text)xpath.selectSingleNode(this.document)); collectionKey = t.getStringValue(); } catch ( Exception e ) { e.printStackTrace(); } return collectionKey; }
private String getValue(String xpath) { XPath xpathObj = DocumentHelper.createXPath(xpath); xpathObj.setNamespaceURIs(getNSMap()); Node node = xpathObj.selectSingleNode(doc); if (node != null) return node.getText(); else return null; }
private String getValue (String xpath) { XPath xpathObj = DocumentHelper.createXPath(xpath); xpathObj.setNamespaceURIs(getNSMap()); Node node = xpathObj.selectSingleNode(doc); if (node != null) return node.getText(); else return null; }
private List getValues(String xpath) { XPath xpathObj = DocumentHelper.createXPath(xpath); xpathObj.setNamespaceURIs(getNSMap()); List nodes = xpathObj.selectNodes(doc); List values = new ArrayList(); for (Iterator i = nodes.iterator(); i.hasNext(); ) { values.add(((Node) i.next()).getText()); } return values; }
/** * Constructs the infoXML abstraction based on the input * given. * * @param _xml */ public InfoXML ( String _xml ) { try { // TODO : BARFS on the xsi: attribute on return saying : // org.dom4j.DocumentException: Error on line 1 of document : // The prefix "xsi" for attribute "xsi:schemaLocation" associated with // an element type "NSDLDataRepository" is not bound. // Nested exception: The prefix "xsi" for attribute "xsi:schemaLocation" // associated with an element type "NSDLDataRepository" is not bound. this.contentRaw = _xml; this.infoxmlDoc = DocumentHelper.parseText( this.contentRaw ); XPath xpath = DocumentHelper.createXPath( "//ndr:error" ); // for error node checks // TODO : though the default namespace is NOT called NDR, // http://www.xslt.com/html/xsl-list/2005-03/msg01059.html indicates we must give // it one if we are to use it in an XPath. How fun is that! SimpleNamespaceContext ns = new SimpleNamespaceContext(); ns.addNamespace("ndr", "http://ns.nsdl.org/ndr/response_v1.00/"); xpath.setNamespaceContext(ns); // select the error node Element error = (Element)xpath.selectSingleNode(this.infoxmlDoc); if ( error != null ) { this.hasErrors = true; this.errorString = error.getText(); } } catch ( Exception e ) { this.contentRaw = _xml; this.errorString = "Fatal error in InfoXML construction."; // e.printStackTrace(); } }
/** * 解析测试套件配置文件 * @param suiteInputStream 配置文件输入流 * @return 测试套件对象 * @throws DocumentException */ public Suite parse(InputStream suiteInputStream) throws DocumentException { SAXReader reader = new SAXReader(); reader.setEncoding("utf-8"); Document document = reader.read(suiteInputStream); simpleNamespaceContext.addNamespace("ns", NS_URI); XPath xpath = new DefaultXPath("/ns:suite"); xpath.setNamespaceContext(simpleNamespaceContext); Element suiteEle = (Element) xpath.selectSingleNode(document); if (suiteEle == null) { suiteEle = document.getRootElement(); // throw new RuntimeException("Can not found suite config."); } Suite suite = new Suite(); String xmlConfPath = suiteEle.attributeValue("pageConfig"); String pagePackage = suiteEle.attributeValue("pagePackage", ""); String rows = suiteEle.attributeValue("rows", "1"); String lackLines = suiteEle.attributeValue("lackLines", "nearby"); String errorLines = suiteEle.attributeValue("errorLines", "stop"); String afterSleep = suiteEle.attributeValue("afterSleep", "0"); suite.setXmlConfPath(xmlConfPath); suite.setPagePackage(pagePackage); suite.setRows(rows); suite.setLackLines(lackLines); suite.setErrorLines(errorLines); suite.setAfterSleep(Long.parseLong(afterSleep)); pagesParse(document, suite); return suite; }
private XPath createXPath( String xpathExpr ) { XPath xpath = document.createXPath( xpathExpr ); if ( !this.namespaceMap.isEmpty() ) { xpath.setNamespaceURIs( this.namespaceMap ); } return xpath; }
public boolean hasElement( String xpathExpr ) throws XMLException { XPath xpath = createXPath( xpathExpr ); Object evaluated = xpath.selectSingleNode( document ); if ( evaluated == null ) { return false; } return true; }
@SuppressWarnings("unchecked") public List<Element> getElementList( String xpathExpr ) throws XMLException { XPath xpath = createXPath( xpathExpr ); Object evaluated = xpath.evaluate( document ); if ( evaluated == null ) { return null; } /* The xpath.evaluate(Context) method can return: * 1) A Collection or List of dom4j Nodes. * 2) A single dom4j Node. */ if ( evaluated instanceof List ) { return (List<Element>) evaluated; } else if ( evaluated instanceof Node ) { List<Element> ret = new ArrayList<>(); ret.add( (Element) evaluated ); return ret; } else { // Unknown evaluated type. throw new XMLException( ".getElementList( Expr: " + xpathExpr + " ) resulted in non-List type -> (" + evaluated.getClass().getName() + ") " + evaluated ); } }
/** * Extracts the value of the supplied attribute * * @param element * element with attribute in question * @param attributeName * name of the attribute in question * @return value of the attribute in question * @throws GenericArtifactParsingException * exception s thrown is attribute is missing */ private static String getAttributeValue(Element element, String attributeName) throws GenericArtifactParsingException { // TODO Cash constructed XPath objects? // XPath xpath = new DefaultXPath("@" + CCF_NAMESPACE_PREFIX + ":" + // attributeName); XPath xpath = new DefaultXPath("@" + attributeName); xpath.setNamespaceURIs(ccfNamespaceMap); Node attributeNode = xpath.selectSingleNode(element); if (attributeNode == null) throw new GenericArtifactParsingException("Missing attribute: " + attributeName + " in element " + element.getName()); else return attributeNode.getText(); }
/** * Extracts the value of the supplied attribute without throwing an * exception if missing * * @param element * element with attribute in question * @param attributeName * name of the attribute in question * @return value of the attribute in question, null if attribute is missing * */ private static String getAttributeValueWithoutException(Element element, String attributeName) { // TODO Cash constructed XPath objects? // XPath xpath = new DefaultXPath("@" + CCF_NAMESPACE_PREFIX + ":" + // attributeName); XPath xpath = new DefaultXPath("@" + attributeName); xpath.setNamespaceURIs(ccfNamespaceMap); Node attributeNode = xpath.selectSingleNode(element); if (attributeNode == null) return null; else return attributeNode.getText(); }
private static XPath buildXpath(Element xslt, final String functionCall) { XPath xpath = xslt.createXPath(String.format( "//xsl:value-of[@select='%s']", functionCall)); SimpleNamespaceContext namespaceContext = new SimpleNamespaceContext(); namespaceContext.addNamespace("xsl", "http://www.w3.org/1999/XSL/Transform"); xpath.setNamespaceContext(namespaceContext); return xpath; }
static List<Element> findFunctionCalls(Element xslt, final String functionCall) { XPath xpath = buildXpath(xslt, functionCall); @SuppressWarnings("unchecked") // jaxen doesn't do generics List<Element> nodes = xpath.selectNodes(xslt); return nodes; }