javax.xml.xpath.XPath#evaluate ( )源码实例Demo

下面列出了javax.xml.xpath.XPath#evaluate ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: mojito   文件: XliffUtils.java
/**
 * Gets the target language of the XLIFF by looking at the first "file" 
 * element.
 *
 * @param xliffContent xliff content from which to extract the target language
 * @return the target language or {@code null} if not found
 */
public String getTargetLanguage(String xliffContent) {

    String targetLanguage = null;

    InputSource inputSource = new InputSource(new StringReader(xliffContent));
    XPath xPath = XPathFactory.newInstance().newXPath();
    
    SimpleNamespaceContext simpleNamespaceContext = new SimpleNamespaceContext();
    simpleNamespaceContext.bindNamespaceUri("xlf", "urn:oasis:names:tc:xliff:document:1.2");
    xPath.setNamespaceContext(simpleNamespaceContext);
    
    try {
        Node node = (Node) xPath.evaluate("/xlf:xliff/xlf:file[1]/@target-language", inputSource, XPathConstants.NODE);
        
        if(node != null) {
            targetLanguage = node.getTextContent();
        }
        
    } catch (XPathExpressionException xpee) {
        logger.debug("Can't extract target language from xliff", xpee);
    }
    return targetLanguage;
}
 
源代码2 项目: freehealth-connector   文件: KmehrHelper.java
private boolean verifyXpath(String[] xpathConfigs, Document doc) throws XPathExpressionException, NumberFormatException, IntegrationModuleException {
    if (xpathConfigs == null) {
        return false;
    }
    String xpathStr = xpathConfigs[0];
    int min = Integer.parseInt(xpathConfigs[1].trim());
    int max = xpathConfigs.length > 2 ? Integer.parseInt(xpathConfigs[2].trim()) : Integer.MAX_VALUE;

    XPath xpath = XPathFactory.newInstance().newXPath();
    NamespaceContext nsCtx = new MapNamespaceContext();
    xpath.setNamespaceContext(nsCtx);
    NodeList nodes = (NodeList) xpath.evaluate(xpathStr, doc, XPathConstants.NODESET);

    if (nodes.getLength() < min || nodes.getLength() > max) {
        LOG.error("FAILED Xpath query : " + xpathStr);
        return false;
        //throw new IntegrationModuleException(I18nHelper.getLabel("error.xml.invalid"));
    }
    return true;
}
 
源代码3 项目: freehealth-connector   文件: KmehrHelper.java
private boolean verifyXpath(String[] xpathConfigs1, String[] xpathConfigs2, Document doc) throws XPathExpressionException {
    if (xpathConfigs1 == null || xpathConfigs2 == null) {
        return false;
    }
    String xpathStr1 = xpathConfigs1[0];
    String xpathStr2 = xpathConfigs2[0];

    XPath xpath = XPathFactory.newInstance().newXPath();
    NamespaceContext nsCtx = new MapNamespaceContext();
    xpath.setNamespaceContext(nsCtx);
    Double count1 = (Double) xpath.evaluate(xpathStr1, doc, XPathConstants.NUMBER);
    Double count2 = (Double) xpath.evaluate(xpathStr2, doc, XPathConstants.NUMBER);

    if (!Objects.equals(count1, count2)) {
        LOG.error("FAILED Xpath query : " + xpathStr1 + " <==> " + xpathStr2);
        return false;
    }
    return true;
}
 
源代码4 项目: waltz   文件: SvgUtilities.java
public static String convertVisioSvg(String key, String svgStr) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException, TransformerException {
    DocumentBuilder builder = createNonValidatingDocumentBuilderFactory().newDocumentBuilder();
    InputSource svgSource = new InputSource(new ByteArrayInputStream(svgStr.getBytes()));
    Document svg = builder.parse(svgSource);

    XPath xpath = XPathFactory.newInstance().newXPath();
    NodeList nodes = (NodeList) xpath.evaluate("//*", svg, XPathConstants.NODESET);

    stream(nodes)
            .forEach(n -> stream(n.getChildNodes())
                    .filter(c -> c.getNodeName().contains("custProps"))
                    .forEach(c -> stream(c.getChildNodes())
                            .filter(cp -> cp.getNodeName().contains("cp"))
                            .map(cp -> (Element) cp)
                            .filter(cp -> key.equals(cp.getAttribute("v:lbl")))
                            .map(cp -> cp.getAttribute("v:val"))
                            .map(v -> v.replaceAll("^.*\\((.*)\\)$", "$1"))
                            .forEach(v -> ((Element) n).setAttribute("data-"+key, v))
                    )
            );

    return printDocument(svg, false); // do NOT toPrettyString print visio
}
 
源代码5 项目: openjdk-jdk9   文件: Bug4991939.java
@Test
public void testXPath13() throws Exception {
    QName qname = new QName(XMLConstants.XML_NS_URI, "");

    XPathFactory xpathFactory = XPathFactory.newInstance();
    Assert.assertNotNull(xpathFactory);

    XPath xpath = xpathFactory.newXPath();
    Assert.assertNotNull(xpath);

    try {
        xpath.evaluate("1+1", (Object) null, qname);
        Assert.fail("failed , expected IAE not thrown");
    } catch (IllegalArgumentException e) {
        ; // as expected
    }
}
 
源代码6 项目: rice   文件: XMLSearchableAttributeContent.java
String getSearchContent() throws XPathExpressionException, ParserConfigurationException {
    if (searchContent == null) {
        Node cfg = getSearchingConfig();
        XPath xpath = XPathHelper.newXPath();
        Node n = (Node) xpath.evaluate("xmlSearchContent", cfg, XPathConstants.NODE);
        if (n != null) {
            StringBuilder sb = new StringBuilder();
            NodeList list = n.getChildNodes();
            for (int i = 0; i < list.getLength(); i++) {
                sb.append(XmlJotter.jotNode(list.item(i)));
            }
            this.searchContent = sb.toString();
        }
    }
    return searchContent;
}
 
源代码7 项目: buck   文件: AndroidManifest.java
@NonNull
private static String getStringValue(@NonNull IAbstractFile file, @NonNull String xPath)
        throws StreamException {
    XPath xpath = AndroidXPathFactory.newXPath();

    InputStream is = null;
    try {
        is = file.getContents();
        return xpath.evaluate(xPath, new InputSource(is));
    } catch (XPathExpressionException e){
        throw new RuntimeException(
                "Malformed XPath expression when reading the attribute from the manifest,"
                        + "exp = " + xPath,
                e);
    } finally {
        Closeables.closeQuietly(is);
    }
}
 
源代码8 项目: development   文件: WebserviceSAMLSPTestSetup.java
private void updateElementValue(XPath path, Document doc, String pathValue,
        String attribute, String value) throws XPathExpressionException {
    Element node = (Element) path.evaluate(pathValue, doc,
            XPathConstants.NODE);
    if (node != null) {
        node.setAttribute(attribute, value);
    }
}
 
源代码9 项目: piranha   文件: WebXmlParser.java
/**
 * Parse the default-context-path section.
 *
 * @param webXml the web.xml to add to.
 * @param xPath the XPath to use.
 * @param node the DOM node.
 */
private void parseDefaultContextPath(WebXml webXml, XPath xPath, Node node) {
    try {
        Node contextPathNode = (Node) xPath.evaluate("//default-context-path", node, NODE);
        if (contextPathNode != null) {
            String defaultContextPath = parseString(xPath, "//default-context-path/text()", node);
            if (defaultContextPath != null) {
                webXml.setDefaultContextPath(defaultContextPath);
            }
        }
    } catch (XPathException xpe) {
        LOGGER.log(WARNING, "Unable to parse <default-context-path> section", xpe);
    }
}
 
源代码10 项目: onos   文件: MockDriverHandler.java
@SuppressWarnings("unchecked")
public MockDriverHandler(Class<? extends AbstractDriverLoader> loaderClass, String behaviorSpec,
        DeviceId mockDeviceId, CoreService mockCoreService, DeviceService mockDeviceService) {

    // Had to split into declaration and initialization to make stylecheck happy
    // else line was considered too long
    // and auto format couldn't be tweak to make it correct
    Map<Class<? extends Behaviour>, Class<? extends Behaviour>> behaviours;
    behaviours = new HashMap<Class<? extends Behaviour>, Class<? extends Behaviour>>();

    try {
        String data = Resources.toString(Resources.getResource(loaderClass, behaviorSpec), StandardCharsets.UTF_8);
        InputStream resp = IOUtils.toInputStream(data, StandardCharsets.UTF_8);
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        Document document = builder.parse(resp);

        XPath xp = XPathFactory.newInstance().newXPath();
        NodeList list = (NodeList) xp.evaluate("//behaviour", document, XPathConstants.NODESET);
        for (int i = 0; i < list.getLength(); i += 1) {
            Node node = list.item(i);
            NamedNodeMap attrs = node.getAttributes();
            Class<? extends Behaviour> api = (Class<? extends Behaviour>) Class
                    .forName(attrs.getNamedItem("api").getNodeValue());
            Class<? extends Behaviour> impl = (Class<? extends Behaviour>) Class
                    .forName(attrs.getNamedItem("impl").getNodeValue());
            behaviours.put(api, impl);
        }
        init(behaviours, mockDeviceId, mockCoreService, mockDeviceService);
    } catch (Exception e) {
        fail(e.toString());
    }
}
 
源代码11 项目: BotLibre   文件: Http.java
/**
 * Post the XML document object and return the XML data from the URL.
 */
public Vertex postXMLAuth(String url, String user, String password, String agent, Vertex xmlObject, String xpath, Network network) {
	log("POST XML Auth", Level.INFO, url);
	try {
		String data = convertToXML(xmlObject);
		log("POST XML", Level.FINE, data);
		String xml = Utils.httpAuthPOST(url, user, password, agent, "application/xml", data);
		log("XML", Level.FINE, xml);
		InputStream stream = new ByteArrayInputStream(xml.getBytes("utf-8"));
		Element element = parseXML(stream);
		if (element == null) {
			return null;
		}
		XPathFactory factory = XPathFactory.newInstance();
		XPath path = factory.newXPath();
		Object node = path.evaluate(xpath, element, XPathConstants.NODE);
		if (node instanceof Element) {
			return convertElement((Element)node, network);
		} else if (node instanceof Attr) {
			return network.createVertex(((Attr)node).getValue());
		} else if (node instanceof org.w3c.dom.Text) {
			return network.createVertex(((org.w3c.dom.Text)node).getTextContent());
		}
		return null;
	} catch (Exception exception) {
		log(exception);
		return null;
	}
}
 
源代码12 项目: BotLibre   文件: Http.java
/**
 * Post the XML document object and return the XML data from the URL.
 */
public Vertex postXMLAuth(String url, String user, String password, Vertex xmlObject, String xpath, Network network) {
	log("POST XML Auth", Level.INFO, url);
	try {
		String data = convertToXML(xmlObject);
		log("POST XML", Level.FINE, data);
		String xml = Utils.httpAuthPOST(url, user, password, "application/xml", data);
		log("XML", Level.FINE, xml);
		InputStream stream = new ByteArrayInputStream(xml.getBytes("utf-8"));
		Element element = parseXML(stream);
		if (element == null) {
			return null;
		}
		XPathFactory factory = XPathFactory.newInstance();
		XPath path = factory.newXPath();
		Object node = path.evaluate(xpath, element, XPathConstants.NODE);
		if (node instanceof Element) {
			return convertElement((Element)node, network);
		} else if (node instanceof Attr) {
			return network.createVertex(((Attr)node).getValue());
		}
		return null;
	} catch (Exception exception) {
		log(exception);
		return null;
	}
}
 
源代码13 项目: rice   文件: RuleAttributeXmlParser.java
public List parseRuleAttributes(Element element) throws XmlException {
	List ruleAttributes = new ArrayList();
	try {
		XPath xpath = XPathHelper.newXPath();
		NodeList nodeList = (NodeList)xpath.evaluate(XPATH_RULE_ATTRIBUTES, element, XPathConstants.NODESET);
		for (int i = 0; i < nodeList.getLength(); i++) {
			Node ruleAttributeNode = nodeList.item(i);
			ruleAttributes.add(parseRuleAttribute(ruleAttributeNode));
		}
		
		for (Iterator iterator = ruleAttributes.iterator(); iterator.hasNext();) {
			RuleAttribute ruleAttribute = (RuleAttribute) iterator.next();
			try {
                   RuleAttribute existingAttribute = KEWServiceLocator.getRuleAttributeService().findByName(ruleAttribute.getName());
                   if (existingAttribute != null) {
                       ruleAttribute.setId(existingAttribute.getId());
                       ruleAttribute.setVersionNumber(existingAttribute.getVersionNumber());
                   }
			    KEWServiceLocator.getRuleAttributeService().save(ruleAttribute);
			} catch (Exception e) {
                LOG.error("Error saving rule attribute entered by XML", e);
			}
		}
	} catch (XPathExpressionException e1) {
		throw new XmlException("Could not find a rule attribute.", e1);
	}
	return ruleAttributes;
}
 
源代码14 项目: freehealth-connector   文件: XmlSignatureBuilder.java
private static byte[] transform(boolean encapsulate, String xpathLocation, EncapsulationTransformer encapsulationTranformer, Document doc, XMLSignature sig) {
   if (!encapsulate) {
      return ConnectorXmlUtils.toByteArray((Node)sig.getElement());
   } else {
      Node toInsert = doc.adoptNode(encapsulationTranformer.transform(sig.getElement()));
      Node insertBeforeNode = null;
      if (StringUtils.isNotBlank(xpathLocation)) {
         try {
            XPath xPath = XPathFactory.newInstance().newXPath();
            NodeList nodes = (NodeList)xPath.evaluate(xpathLocation, doc.getDocumentElement(), XPathConstants.NODESET);
            if (nodes.getLength() == 1) {
               LOG.debug("1 node found, inserting at location [" + xpathLocation + "]");
               insertBeforeNode = nodes.item(0);
            } else {
               LOG.warn("XPATH error: " + nodes.getLength() + "found at location [" + xpathLocation + "],using default.");
            }
         } catch (XPathExpressionException var9) {
            LOG.info("Unable to determine XPath Location, using default.", var9);
         }
      } else {
         LOG.debug("Using default location (last child tag)");
      }

      doc.getFirstChild().insertBefore(toInsert, insertBeforeNode);
      return ConnectorXmlUtils.toByteArray((Node)doc);
   }
}
 
@Test
public void testDiscoverPortDetails() {
    List<PortDescription> result = new ArrayList<>();
    List<PortDescription> expectResult = getExpectedPorts();

    try {
        XPath xp = XPathFactory.newInstance().newXPath();
        Node nodeListItem;

        Node node = doRequest("/response/discoverPortDetails.xml", "/rpc-reply/data");
        NodeList nodeList = (NodeList) xp.evaluate("waveserver-ports/ports", node, XPathConstants.NODESET);
        int count = nodeList.getLength();
        for (int i = 0; i < count; ++i) {
            nodeListItem = nodeList.item(i);
            DefaultAnnotations annotationPort = DefaultAnnotations.builder()
                    .set(AnnotationKeys.PORT_NAME, xp.evaluate("port-id/text()", nodeListItem))
                    .set(AnnotationKeys.PROTOCOL, xp.evaluate("id/type/text()", nodeListItem))
                    .build();
            String port = xp.evaluate("port-id/text()", nodeListItem);
            result.add(DefaultPortDescription.builder()
                              .withPortNumber(PortNumber.portNumber(
                                      portIdConvert(port), port))
                              .isEnabled(portStateConvert(xp.evaluate(
                                      "state/operational-state/text()", nodeListItem)))
                              .portSpeed(portSpeedToLong(xp.evaluate(
                                      "id/speed/text()", nodeListItem)))
                              .type(Port.Type.PACKET)
                              .annotations(annotationPort)
                              .build());
        }
    } catch (XPathExpressionException e) {
        e.printStackTrace();
    }
     assertEquals(expectResult, result);
}
 
源代码16 项目: rice   文件: XPathQualifierResolver.java
protected void handleSimpleMap(Node baseNode, List<Map<String, String>> maps, ResolverConfig config, XPath xPath) throws XPathExpressionException {
	String attributeName = config.getExpressionMap().keySet().iterator().next();
	String xPathExpression = config.getExpressionMap().get(attributeName);
	NodeList attributes = (NodeList)xPath.evaluate(xPathExpression, baseNode, XPathConstants.NODESET);
	for (int index = 0; index < attributes.getLength(); index++) {
		Element attributeElement = (Element)attributes.item(index);
		Map<String, String> map = new HashMap<String, String>();
		String attributeValue = attributeElement.getTextContent();
		if (LOG.isDebugEnabled()) {
			LOG.debug("Adding values to simple Map<String, String>: " + attributeName + "::" + attributeValue);
		}
		map.put(attributeName, attributeValue);
		maps.add(map);
	}
}
 
源代码17 项目: BotLibre   文件: Http.java
/**
 * GET the XML data from the URL.
 */
public Vertex requestXMLAuth(String url, String user, String password, String xpath, Network network) {
	log("GET XML Auth", Level.INFO, url);
	try {
		String xml = Utils.httpAuthGET(url, user, password);
		log("XML", Level.FINE, xml);
		InputStream stream = new ByteArrayInputStream(xml.getBytes("utf-8"));
		Element element = parseXML(stream);
		if (element == null) {
			return null;
		}
		if (xpath == null) {
			return convertElement(element, network);
		}
		XPathFactory factory = XPathFactory.newInstance();
		XPath path = factory.newXPath();
		Object node = path.evaluate(xpath, element, XPathConstants.NODE);
		if (node instanceof Element) {
			return convertElement((Element)node, network);
		} else if (node instanceof Attr) {
			return network.createVertex(((Attr)node).getValue());
		} else if (node instanceof org.w3c.dom.Text) {
			return network.createVertex(((org.w3c.dom.Text)node).getTextContent());
		}
		return null;
	} catch (Exception exception) {
		log(exception);
		return null;
	}
}
 
源代码18 项目: webcurator   文件: XPathWctMetsExtractor.java
private void populateCopyrightURL(Document doc, XPath xpath) throws XPathExpressionException {
    copyrightURL = (String) xpath.evaluate(copyrightURLQuery, doc, XPathConstants.STRING);
}
 
源代码19 项目: webcurator   文件: XPathWctMetsExtractor.java
private void populateProvenanceNote(Document doc, XPath xpath) throws XPathExpressionException {
    provenanceNote = (String) xpath.evaluate(provenanceNoteQuery, doc, XPathConstants.STRING);
}
 
protected Boolean getBoolean(XPath xpath, String elementName, Document document) throws XPathExpressionException {
    
    Node directive = (Node) xpath.evaluate(elementName, document, XPathConstants.NODE);

    if(directive == null || directive.getTextContent() == null)
        return null;
    
    String val = directive.getTextContent();
    if(val.equalsIgnoreCase("true") || val.equalsIgnoreCase("yes") || val.equalsIgnoreCase("y"))
        return Boolean.TRUE;
    
    return Boolean.FALSE;
}