当前位置: 首页>>代码示例>>Java>>正文


Java XPathConstants类代码示例

本文整理汇总了Java中javax.xml.xpath.XPathConstants的典型用法代码示例。如果您正苦于以下问题:Java XPathConstants类的具体用法?Java XPathConstants怎么用?Java XPathConstants使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


XPathConstants类属于javax.xml.xpath包,在下文中一共展示了XPathConstants类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: selectXMLNode

import javax.xml.xpath.XPathConstants; //导入依赖的package包/类
/**
 * selectXMLNode
 * 
 * @param xpath
 * @return Node
 */
public Node selectXMLNode(String xpath) {

    for (Document doc : this.docs) {
        try {
            Node node = (Node) this.xpath.evaluate(xpath, doc, XPathConstants.NODE);

            if (null != node) {
                return node;
            }

        }
        catch (XPathExpressionException e) {
            if (this.logger.isLogEnabled()) {
                this.logger.warn("Select nodes[" + xpath + "] from doc[" + doc + "] FAILs.", e);
            }
        }
    }

    return null;
}
 
开发者ID:uavorg,项目名称:uavstack,代码行数:27,代码来源:ComponentProfileHandler.java

示例2: getVersion

import javax.xml.xpath.XPathConstants; //导入依赖的package包/类
/**
 * Returns the version
 * 
 * @return String
 */
public static String getVersion() {
    String jarImplementation = VISNode.class.getPackage().getImplementationVersion();
    if (jarImplementation != null) {
        return jarImplementation;
    }
    String file = VISNode.class.getResource(".").getFile();
    String pack = VISNode.class.getPackage().getName().replace(".", "/") + '/';
    File pomXml = new File(file.replace("target/classes/" + pack, "pom.xml"));
    if (pomXml.exists()) {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(new InputSource(new FileReader(pomXml)));
            XPath xPath = XPathFactory.newInstance().newXPath();
            return (String) xPath.evaluate("/project/version", document, XPathConstants.STRING);
        } catch (IOException | ParserConfigurationException | XPathExpressionException | SAXException e) { }
    }
    return "Unknown version";
}
 
开发者ID:VISNode,项目名称:VISNode,代码行数:25,代码来源:VersionFinder.java

示例3: find

import javax.xml.xpath.XPathConstants; //导入依赖的package包/类
public NodeInfoList find(UiElement context) throws Exception {
    Element domNode = getDomNode((UiElement<?, ?>) context);
    NodeInfoList list = new NodeInfoList();
    getDocument().appendChild(domNode);
    NodeList nodes = (NodeList) xPathExpression.evaluate(domNode, XPathConstants.NODESET);
    int nodesLength = nodes.getLength();
    for (int i = 0; i < nodesLength; i++) {
        if (nodes.item(i).getNodeType() == Node.ELEMENT_NODE && !FROM_DOM_MAP.get(nodes.item(i)).getClassName().equals("hierarchy")) {
            list.addToList(FROM_DOM_MAP.get(nodes.item(i)).node);
        }
    }
    try {
        getDocument().removeChild(domNode);
    } catch (DOMException e) {
        document = null;
    }
    return list;
}
 
开发者ID:macacajs,项目名称:UIAutomatorWD,代码行数:19,代码来源:XPathSelector.java

示例4: handleRequireModules

import javax.xml.xpath.XPathConstants; //导入依赖的package包/类
private void handleRequireModules(AddOnVersion addOnVersion, XPath xpath, Document config)
		throws XPathExpressionException {
	NodeList nodeList = (NodeList) xpath.evaluate("/module/require_modules/require_module", config,
			XPathConstants.NODESET);
	for (int i = 0; i < nodeList.getLength(); ++i) {
		Node item = nodeList.item(i);
		Node version = item.getAttributes().getNamedItem("version");
		String requiredModule = item.getTextContent().trim();
		String requiredVersion = version == null ? null : version.getTextContent().trim();
		// sometimes modules are inadvertently uploaded without substituting maven variables in config.xml and we end
		// up with a required module version like ${reportingVersion}
		if (requiredVersion != null && requiredVersion.startsWith("${")) {
			requiredVersion = null;
		}
		addOnVersion.addRequiredModule(requiredModule, requiredVersion);
	}
}
 
开发者ID:openmrs,项目名称:openmrs-contrib-addonindex,代码行数:18,代码来源:FetchDetailsToIndex.java

示例5: unwrapSoapMessage

import javax.xml.xpath.XPathConstants; //导入依赖的package包/类
public Element unwrapSoapMessage(Element soapElement) {
    XPath xpath = XPathFactory.newInstance().newXPath();
    NamespaceContextImpl context = new NamespaceContextImpl();
    context.startPrefixMapping("soapenv", "http://schemas.xmlsoap.org/soap/envelope/");
    context.startPrefixMapping("samlp", "urn:oasis:names:tc:SAML:2.0:protocol");
    context.startPrefixMapping("saml", "urn:oasis:names:tc:SAML:2.0:assertion");
    context.startPrefixMapping("ds", "http://www.w3.org/2000/09/xmldsig#");
    xpath.setNamespaceContext(context);
    try {
        final String expression = "/soapenv:Envelope/soapenv:Body/samlp:Response";
        Element element = (Element) xpath.evaluate(expression, soapElement, XPathConstants.NODE);

        if (element == null) {
            String errorMessage = format("Document{0}{1}{0}does not have element {2} inside it.", NEW_LINE,
                    writeToString(soapElement), expression);
            LOG.error(errorMessage);
            throw new IllegalArgumentException(errorMessage);
        }

        return element;
    } catch (XPathExpressionException e) {
        throw propagate(e);
    }
}
 
开发者ID:alphagov,项目名称:verify-hub,代码行数:25,代码来源:SoapMessageManager.java

示例6: processDocument

import javax.xml.xpath.XPathConstants; //导入依赖的package包/类
/**
 * Check the given document against the list of XPath statements provided.
 * 
 * @param doc          the XML document
 * @return                  Returns a content worker that was matched or <tt>null</tt>
 */
private W processDocument(Document doc)
{
    for (Map.Entry<String, W> entry : workersByXPath.entrySet())
    {
        try
        {
            String xpath = entry.getKey();
            W worker = entry.getValue();
            // Execute the statement
            Object ret = xpathFactory.newXPath().evaluate(xpath, doc, XPathConstants.NODE);
            if (ret != null)
            {
                // We found one
                return worker;
            }
        }
        catch (XPathExpressionException e)
        {
            // We accept this and move on
        }
    }
    // Nothing found
    return null;
}
 
开发者ID:Alfresco,项目名称:alfresco-repository,代码行数:31,代码来源:XPathContentWorkerSelector.java

示例7: getByXpath

import javax.xml.xpath.XPathConstants; //导入依赖的package包/类
/**
 * Get values matching passed XPath expression
 * @param node
 * @param expression XPath expression
 * @return matching values
 * @throws Exception
 */
private static String[] getByXpath( Node node, String expression ) throws Exception {

    XPathFactory xPathFactory = XPathFactory.newInstance();
    XPath xPath = xPathFactory.newXPath();
    XPathExpression xPathExpression = xPath.compile(expression);

    NodeList nlist = (NodeList) xPathExpression.evaluate(node, XPathConstants.NODESET);

    int nodeListSize = nlist.getLength();
    List<String> values = new ArrayList<String>(nodeListSize);
    for (int index = 0; index < nlist.getLength(); index++) {
        Node aNode = nlist.item(index);
        values.add(aNode.getTextContent());
    }
    return values.toArray(new String[values.size()]);
}
 
开发者ID:Axway,项目名称:ats-framework,代码行数:24,代码来源:XmlUtilities.java

示例8: countColumns

import javax.xml.xpath.XPathConstants; //导入依赖的package包/类
protected static void countColumns(XPath xPath, Table table, Node tableHead)
		throws XPathExpressionException, DOMException, NumberFormatException {
	if (tableHead != null) {
		Node firstRow = (Node) xPath.compile("*[1]").evaluate(tableHead, XPathConstants.NODE);
		NodeList childFirstRows = firstRow.getChildNodes();
		int columnNumber = 0;
		for (int w = 0; w < childFirstRows.getLength(); w++) {
			Node childFirstRow = childFirstRows.item(w);
			if (childFirstRow.getNodeValue() == null && (childFirstRow.getNodeName() == "th" || childFirstRow.getNodeName() == "td")) {
				int number = 1;
				if (childFirstRow.getAttributes().getNamedItem("colspan") != null) {
					number = Integer.parseInt(childFirstRow.getAttributes().getNamedItem("colspan").getNodeValue());
				} 
				columnNumber = columnNumber + number;
			}
		}
		table.setColumnNumber(columnNumber);
	}
}
 
开发者ID:Vitaliy-1,项目名称:JATS2LaTeX,代码行数:20,代码来源:TableFunctions.java

示例9: parse

import javax.xml.xpath.XPathConstants; //导入依赖的package包/类
@Override
public void parse(Consumer<MnoInfo> consumer) throws Exception {
    File fXmlFile = config.toFile();

    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(fXmlFile);
    doc.getDocumentElement().normalize();
    XPathExpression xpathMno = XPathFactory.newInstance().newXPath().compile("//*[local-name()='mno']");
    XPathExpression xpathMasksMno = XPathFactory.newInstance().newXPath().compile("//*[local-name()='mask']");
    NodeList mnoNodes = (NodeList) xpathMno.evaluate(doc, XPathConstants.NODESET);
    for (int i=0; i<mnoNodes.getLength(); i++) {
        Node node = mnoNodes.item(i);
        NamedNodeMap attributes = node.getAttributes();
        String country = getValue(attributes.getNamedItem("country"));
        String title = getValue(attributes.getNamedItem("title"));
        String area = getValue(attributes.getNamedItem("area"));
        Set<Mask> masks = new HashSet<>();
        NodeList maskNodes = (NodeList) xpathMasksMno.evaluate(doc, XPathConstants.NODESET);
        for (int j=0; j<maskNodes.getLength(); j++) {
            masks.add(Mask.parse(getValue(maskNodes.item(j))));
        }
        consumer.accept(new MnoInfo(title, area, country, masks));
    }
}
 
开发者ID:chukanov,项目名称:mnp,代码行数:26,代码来源:CustomMasksParser.java

示例10: performFileExistenceChecks

import javax.xml.xpath.XPathConstants; //导入依赖的package包/类
/**
 * Performs all file existence checks contained in the validation profile. If the validation has failed (some of the files specified
 * in the validation profile do not exist), {@link MissingFile} exception is thrown.
 *
 * @param sipPath path to the SIP
 * @param validationProfileDoc document with the validation profile
 * @param validationProfileId id of the validation profile
 * @throws XPathExpressionException if there is an error in the XPath expression
 */
private void performFileExistenceChecks(String sipPath, Document validationProfileDoc, String validationProfileId) throws
        XPathExpressionException {
    XPath xPath =  XPathFactory.newInstance().newXPath();

    NodeList nodes = (NodeList) xPath.compile("/profile/rule/fileExistenceCheck")
            .evaluate(validationProfileDoc, XPathConstants.NODESET);
    for (int i = 0; i< nodes.getLength(); i++) {

        Element element = (Element) nodes.item(i);
        String relativePath = element.getElementsByTagName("filePath").item(0).getTextContent();
        String absolutePath = sipPath + relativePath;
        if (!ValidationChecker.fileExists(absolutePath)) {
            log.info("Validation of SIP with profile " + validationProfileId + " failed. File at \"" + relativePath + "\" is missing.");
            throw new MissingFile(relativePath, validationProfileId);
        }
    }
}
 
开发者ID:LIBCAS,项目名称:ARCLib,代码行数:27,代码来源:ValidationService.java

示例11: performValidationSchemaChecks

import javax.xml.xpath.XPathConstants; //导入依赖的package包/类
/**
 * Performs all validation schema checks contained in the validation profile. If the validation has failed (some of the XMLs
 * specified in the validation profile do not match their respective validation schemas) {@link SchemaValidationError} is thrown.
 *
 * @param sipPath path to the SIP
 * @param validationProfileDoc document with the validation profile
 * @param validationProfileId id of the validation profile
 * @throws IOException if some of the XMLs address from the validation profile does not exist
 * @throws XPathExpressionException if there is an error in the XPath expression
 * @throws SAXException if the XSD schema is invalid
 */
private void performValidationSchemaChecks(String sipPath, Document validationProfileDoc, String validationProfileId) throws
        XPathExpressionException, IOException, SAXException {
    XPath xPath =  XPathFactory.newInstance().newXPath();

    NodeList nodes = (NodeList) xPath.compile("/profile/rule/validationSchemaCheck")
            .evaluate(validationProfileDoc,
                    XPathConstants.NODESET);
    for (int i = 0; i< nodes.getLength(); i++) {
        Element element = (Element) nodes.item(i);
        String filePath = element.getElementsByTagName("filePath").item(0).getTextContent();
        String schema = element.getElementsByTagName("schema").item(0).getTextContent();

        String absoluteFilePath = sipPath + filePath;

        try {
            ValidationChecker.validateWithXMLSchema(new FileInputStream(absoluteFilePath), new InputStream[] {
                    new ByteArrayInputStream(schema.getBytes(StandardCharsets.UTF_8.name()))});
        } catch (GeneralException e) {
            log.info("Validation of SIP with profile " + validationProfileId + " failed. File at \"" + filePath + "\" is not " +
                    "valid against its corresponding schema.");
            throw new SchemaValidationError(filePath, schema, e.getMessage());
        }
    }
}
 
开发者ID:LIBCAS,项目名称:ARCLib,代码行数:36,代码来源:ValidationService.java

示例12: testXPath11

import javax.xml.xpath.XPathConstants; //导入依赖的package包/类
@Test
public void testXPath11() throws Exception {
    try {
        Document d = null;

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

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

        String quantity = (String) xpath.evaluate("/widgets/widget[@name='a']/@quantity", d, XPathConstants.STRING);
        Assert.fail("XPathExpressionException not thrown");
    } catch (XPathExpressionException e) {
        // Expected exception as context node is null
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:18,代码来源:Bug4991857.java

示例13: getNodeList

import javax.xml.xpath.XPathConstants; //导入依赖的package包/类
public static Iterator<Node> getNodeList(String exp, Element dom) throws XPathExpressionException {
	XPath xpath = XPathFactory.newInstance().newXPath();
	XPathExpression expUserTask = xpath.compile(exp);
	final NodeList nodeList = (NodeList) expUserTask.evaluate(dom, XPathConstants.NODESET);

	return new Iterator<Node>() {
		private int index = 0;

		@Override
		public Node next() {
			return nodeList.item(index++);
		}

		@Override
		public boolean hasNext() {
			return (nodeList.getLength() - index) > 0;
		}
	};
}
 
开发者ID:DataAgg,项目名称:DaUtil,代码行数:20,代码来源:DomXmlUtils.java

示例14: execute

import javax.xml.xpath.XPathConstants; //导入依赖的package包/类
@SuppressWarnings("nls")
@Override
public void execute(TemporaryFileHandle staging, InstitutionInfo instInfo, ConverterParams params)
	throws XPathExpressionException
{
	SubTemporaryFile folder = new SubTemporaryFile(staging, "workflow");
	List<String> entries = xmlHelper.getXmlFileList(folder);
	for( String entry : entries )
	{
		PropBagEx workflow = xmlHelper.readToPropBagEx(folder, entry);
		NodeList zeroDays = (NodeList) allNodes.evaluate(workflow.getRootElement(), XPathConstants.NODESET);
		for( int i = 0; i < zeroDays.getLength(); i++ )
		{
			PropBagEx bag = new PropBagEx(zeroDays.item(i), true);
			bag.setNode("priority", Priority.NORMAL.intValue());
			if( bag.isNodeTrue("escalate") && bag.getIntNode("escalationdays") == 0 )
			{
				bag.setNode("escalate", "false");
			}
		}
		xmlHelper.writeFromPropBagEx(folder, entry, workflow);
	}
}
 
开发者ID:equella,项目名称:Equella,代码行数:24,代码来源:AddNotificationSchemaXML.java

示例15: getMaxRId

import javax.xml.xpath.XPathConstants; //导入依赖的package包/类
private int getMaxRId(ByteArrayOutputStream xmlStream) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {

		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		Document doc = builder.parse(new ByteArrayInputStream(xmlStream.toByteArray()));
		XPathFactory xPathfactory = XPathFactory.newInstance();
		XPath xpath = xPathfactory.newXPath();
		XPathExpression expr = xpath.compile("Relationships/*");
		NodeList nodeList = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
		for (int i = 0; i < nodeList.getLength(); i++) {
			String id = nodeList.item(i).getAttributes().getNamedItem("Id").getTextContent();
			int idNum = Integer.parseInt(id.substring("rId".length()));
			this.maxRId = idNum > this.maxRId ? idNum : this.maxRId;
		}
		return this.maxRId;
	}
 
开发者ID:dvbern,项目名称:doctemplate,代码行数:17,代码来源:DOCXMergeEngine.java


注:本文中的javax.xml.xpath.XPathConstants类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。