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


Java XPathFactory类代码示例

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


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

示例1: getPublicationsForAuthor

import org.jdom2.xpath.XPathFactory; //导入依赖的package包/类
public Set<Element> getPublicationsForAuthor(PublicationAuthor author)
		throws IOException, JDOMException, SAXException {
	if (!author.getScopusAuthorID().isEmpty()) {
		Set<Element> publications = new HashSet<>();
		String queryURL = API_URL + "/author/AUTHOR_ID:" + author.getScopusAuthorID()
				+ "?start=0&count=200&view=DOCUMENTS&apikey=" + API_KEY;
		XPathExpression<Element> xPath = XPathFactory.instance().compile(pathToDocumentIdentifier,
				Filters.element());
		List<Element> identifierElements = xPath
				.evaluate(getResponse(queryURL).asXML().detachRootElement().clone());
		for (Element idElement : identifierElements) {
			publications.add(getPublicationByID(idElement.getValue()));
		}
		return publications;
	} else
		return null;
}
 
开发者ID:ETspielberg,项目名称:bibliometrics,代码行数:18,代码来源:ScopusConnector.java

示例2: getCitationInformation

import org.jdom2.xpath.XPathFactory; //导入依赖的package包/类
public Element getCitationInformation(String scopusID)
		throws IOException, JDOMException, SAXException {
	// build API URL
	String queryURL = API_URL + "/abstract/citation-count?scopus_id=" + scopusID + "&apikey=" + API_KEY
			+ "&httpAccept=application%2Fxml";
	XPathExpression<Element> xPathCount = XPathFactory.instance().compile(pathToCitationCount, Filters.element());
	XPathExpression<Element> xPathLink = XPathFactory.instance().compile(pathToCitationLink, Filters.element());
	XPathExpression<Element> xPathArticleLink = XPathFactory.instance().compile(pathToArticleLink, Filters.element());
	Element response = getResponse(queryURL).asXML().detachRootElement().clone();
	String citationCount = xPathCount.evaluateFirst(response).getValue();
	String citationLink = xPathLink.evaluateFirst(response).getAttributeValue("href");
	String articleLink = xPathArticleLink.evaluateFirst(response).getAttributeValue("href");
	Element citationInformation = new Element("citationInformation");
	citationInformation.addContent(new Element("count").setText(citationCount));
	citationInformation.addContent(new Element("citationLink").setText(citationLink));
	citationInformation.addContent(new Element("articleLink").setText(articleLink));
	return citationInformation;
}
 
开发者ID:ETspielberg,项目名称:bibliometrics,代码行数:19,代码来源:ScopusConnector.java

示例3: load

import org.jdom2.xpath.XPathFactory; //导入依赖的package包/类
@Override
public TestCaseData load() {
    TestCaseData tcData = new TestCaseData();

    XPathFactory xFactory = XPathFactory.instance();

    Element testCase = xFactory.compile("//testcase[@name='" + name + "']", Filters.element()).evaluateFirst(xmlDocument);

    List<Element> scenarios = testCase.getChildren();

    for (Element scenario : scenarios) {
        List<Element> parameters = scenario.getChildren();
        ScenarioData testScenario = new ScenarioData(scenario.getName(), testCase.getName());

        for (Element parameter : parameters) {
            testScenario.putScenarioData(parameter.getName(), parameter.getValue());
        }

        tcData.addScenarioData(testScenario);
    }

    return tcData;
}
 
开发者ID:AgileTestingFramework,项目名称:atf-toolbox-java,代码行数:24,代码来源:XMLDataDriver.java

示例4: bind

import org.jdom2.xpath.XPathFactory; //导入依赖的package包/类
private void bind(String xPath, boolean buildIfNotExists, String initialValue) throws JaxenException {
    this.xPath = xPath;

    Map<String, Object> variables = buildXPathVariables();

    XPathExpression<Object> xPathExpr = XPathFactory.instance().compile(xPath, Filters.fpassthrough(), variables,
        MCRConstants.getStandardNamespaces());

    boundNodes.addAll(xPathExpr.evaluate(parent.getBoundNodes()));

    for (Object boundNode : boundNodes)
        if (!(boundNode instanceof Element || boundNode instanceof Attribute || boundNode instanceof Document))
            throw new RuntimeException(
                "XPath MUST only bind either element, attribute or document nodes: " + xPath);

    LOGGER.debug("Bind to {} selected {} node(s)", xPath, boundNodes.size());

    if (boundNodes.isEmpty() && buildIfNotExists) {
        MCRNodeBuilder builder = new MCRNodeBuilder(variables);
        Object built = builder.buildNode(xPath, initialValue, (Parent) (parent.getBoundNode()));
        LOGGER.debug("Bind to {} generated node {}", xPath, MCRXPathBuilder.buildXPath(built));
        boundNodes.add(built);
        trackNodeCreated(builder.getFirstNodeBuilt());
    }
}
 
开发者ID:MyCoRe-Org,项目名称:mycore,代码行数:26,代码来源:MCRBinding.java

示例5: testUpdate

import org.jdom2.xpath.XPathFactory; //导入依赖的package包/类
@Test
public void testUpdate() throws IOException, URISyntaxException, MCRPersistenceException,
    MCRActiveLinkException, JDOMException, SAXException, MCRAccessException {
    MCRObject seriesNew = new MCRObject(getResourceAsURL(seriesID + "-updated.xml").toURI());
    MCRMetadataManager.update(seriesNew);
    Document bookNew = MCRXMLMetadataManager.instance().retrieveXML(bookID);
    XPathBuilder<Element> builder = new XPathBuilder<>(
        "/mycoreobject/metadata/def.modsContainer/modsContainer/mods:mods/mods:relatedItem/mods:titleInfo/mods:title",
        Filters.element());
    builder.setNamespace(MCRConstants.MODS_NAMESPACE);
    XPathExpression<Element> seriesTitlePath = builder.compileWith(XPathFactory.instance());
    Element titleElement = seriesTitlePath.evaluateFirst(bookNew);
    Assert.assertNotNull(
        "No title element in related item: " + new XMLOutputter(Format.getPrettyFormat()).outputString(bookNew),
        titleElement);
    Assert.assertEquals("Title update from series was not promoted to book of series.",
        "Updated series title", titleElement.getText());
}
 
开发者ID:MyCoRe-Org,项目名称:mycore,代码行数:19,代码来源:MCRMODSLinkedMetadataTest.java

示例6: extractModsMetadata

import org.jdom2.xpath.XPathFactory; //导入依赖的package包/类
@Override
public List<MCRIIIFMetadata> extractModsMetadata(Element xmlData) {
    Map<String, String> elementLabelMap = new HashMap<>();

    elementLabelMap.put("title", "mods:mods/mods:titleInfo/mods:title/text()");
    elementLabelMap.put("genre", "mods:mods/mods:genre/text()");
    // TODO: add some more metadata

    return elementLabelMap.entrySet().stream().map(entry -> {
        XPathExpression<Text> pathExpression = XPathFactory.instance().compile(entry.getValue(), Filters.text(),
            null, MCRConstants.MODS_NAMESPACE);
        List<Text> texts = pathExpression.evaluate(xmlData);
        if (texts.size() == 0) {
            return null;
        }
        return new MCRIIIFMetadata(entry.getKey(),
            texts.stream().map(Text::getText).collect(Collectors.joining(", ")));
    }).filter(Objects::nonNull)
        .collect(Collectors.toList());
}
 
开发者ID:MyCoRe-Org,项目名称:mycore,代码行数:21,代码来源:MCRMetsIIIFModsMetadataExtractor.java

示例7: searchFileInGroup

import org.jdom2.xpath.XPathFactory; //导入依赖的package包/类
/**
 * Searches a file in a group, which matches a filename.
 *
 * @param mets the mets file to search
 * @param path the path to the alto file (e.g. "alto/alto_file.xml" when searching in DEFAULT_FILE_GROUP_USE or
 *             "image_file.jpg" when searchin in ALTO_FILE_GROUP_USE)
 * @param searchFileGroup
 * @return the id of the matching file or null if there is no matching file
 */
private static String searchFileInGroup(Document mets, String path, String searchFileGroup) {
    XPathExpression<Element> xpath;// first check all files in default file group
    String relatedFileExistPathString = String.format(Locale.ROOT,
        "mets:mets/mets:fileSec/mets:fileGrp[@USE='%s']/mets:file/mets:FLocat", searchFileGroup);
    xpath = XPathFactory.instance().compile(relatedFileExistPathString, Filters.element(), null,
        MCRConstants.METS_NAMESPACE, MCRConstants.XLINK_NAMESPACE);
    List<Element> fileLocList = xpath.evaluate(mets);
    String matchId = null;

    // iterate over all files
    path = getCleanPath(path);

    for (Element fileLoc : fileLocList) {
        Attribute hrefAttribute = fileLoc.getAttribute("href", MCRConstants.XLINK_NAMESPACE);
        String hrefAttributeValue = hrefAttribute.getValue();
        String hrefPath = getCleanPath(removeExtension(hrefAttributeValue));

        if (hrefPath.equals(removeExtension(path))) {
            matchId = ((Element) fileLoc.getParent()).getAttributeValue("ID");
            break;
        }
    }
    return matchId;
}
 
开发者ID:MyCoRe-Org,项目名称:mycore,代码行数:34,代码来源:MCRMetsSave.java

示例8: testToXML

import org.jdom2.xpath.XPathFactory; //导入依赖的package包/类
@Test
public void testToXML() throws Exception {
    Document document = MCRSimpleModelXMLConverter.toXML(metsSimpleModel);

    XPathFactory xPathFactory = XPathFactory.instance();
    String documentAsString = new XMLOutputter(Format.getPrettyFormat()).outputString(document);

    Arrays.asList(PATHS_TO_CHECK.split(";")).stream()
        .map((String xpath) -> xPathFactory.compile(xpath, Filters.fboolean(), Collections.emptyMap(),
            Namespace.getNamespace("mets", "http://www.loc.gov/METS/")))
        .forEachOrdered(xPath -> {
            Boolean evaluate = xPath.evaluateFirst(document);
            Assert.assertTrue(
                String.format("The xpath : %s is not true! %s %s", xPath, System.lineSeparator(), documentAsString),
                evaluate);
        });
}
 
开发者ID:MyCoRe-Org,项目名称:mycore,代码行数:18,代码来源:MCRSimpleModelXMLConverterTest.java

示例9: getIdentifier

import org.jdom2.xpath.XPathFactory; //导入依赖的package包/类
@Override
public Optional<MCRPersistentIdentifier> getIdentifier(MCRBase obj, String additional)
    throws MCRPersistentIdentifierException {
    String xpath = getProperties().get("Xpath");
    Document xml = obj.createXML();
    XPathFactory xpfac = XPathFactory.instance();
    XPathExpression<Text> xp = xpfac.compile(xpath, Filters.text());
    List<Text> evaluate = xp.evaluate(xml);
    if (evaluate.size() > 1) {
        throw new MCRPersistentIdentifierException(
            "Got " + evaluate.size() + " matches for " + obj.getId() + " with xpath " + xpath + "");
    }

    if (evaluate.size() == 0) {
        return Optional.empty();
    }

    Text identifierText = evaluate.listIterator().next();
    String identifierString = identifierText.getTextNormalize();

    Optional<MCRDNBURN> parsedIdentifierOptional = PARSER.parse(identifierString);
    return parsedIdentifierOptional.map(MCRPersistentIdentifier.class::cast);
}
 
开发者ID:MyCoRe-Org,项目名称:mycore,代码行数:24,代码来源:MCRURNObjectXPathMetadataManager.java

示例10: writeXML

import org.jdom2.xpath.XPathFactory; //导入依赖的package包/类
/**
 * Output xml
 * @param eRoot - the root element
 * @param lang - the language which should be filtered or null for no filter
 * @return a string representation of the XML
 * @throws IOException
 */
private static String writeXML(Element eRoot, String lang) throws IOException {
    StringWriter sw = new StringWriter();
    if (lang != null) {
        // <label xml:lang="en" text="part" />
        XPathExpression<Element> xpE = XPathFactory.instance().compile("//label[@xml:lang!='" + lang + "']",
            Filters.element(), null, Namespace.XML_NAMESPACE);
        for (Element e : xpE.evaluate(eRoot)) {
            e.getParentElement().removeContent(e);
        }
    }
    XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat());
    Document docOut = new Document(eRoot.detach());
    xout.output(docOut, sw);
    return sw.toString();
}
 
开发者ID:MyCoRe-Org,项目名称:mycore,代码行数:23,代码来源:MCRRestAPIClassifications.java

示例11: createXMLForSubdirectories

import org.jdom2.xpath.XPathFactory; //导入依赖的package包/类
private static void createXMLForSubdirectories(MCRPath mcrPath, Element currentElement, int currentDepth,
    int maxDepth) {
    if (currentDepth < maxDepth) {
        XPathExpression<Element> xp = XPathFactory.instance().compile("./children/child[@type='directory']",
            Filters.element());
        for (Element e : xp.evaluate(currentElement)) {
            String name = e.getChildTextNormalize("name");
            try {
                MCRPath pChild = (MCRPath) mcrPath.resolve(name);
                Document doc = MCRPathXML.getDirectoryXML(pChild);
                Element eChildren = doc.getRootElement().getChild("children");
                if (eChildren != null) {
                    e.addContent(eChildren.detach());
                    createXMLForSubdirectories(pChild, e, currentDepth + 1, maxDepth);
                }
            } catch (IOException ex) {
                //ignore
            }

        }
    }
}
 
开发者ID:MyCoRe-Org,项目名称:mycore,代码行数:23,代码来源:MCRRestAPIObjectsHelper.java

示例12: transform

import org.jdom2.xpath.XPathFactory; //导入依赖的package包/类
protected InputStream transform(String xmlFile) throws Exception {
    InputStream guiXML = getClass().getResourceAsStream(xmlFile);
    if (guiXML == null) {
        throw new WebApplicationException(Response.status(Status.INTERNAL_SERVER_ERROR).build());
    }
    SAXBuilder saxBuilder = new SAXBuilder();
    Document webPage = saxBuilder.build(guiXML);
    XPathExpression<Object> xpath = XPathFactory.instance().compile(
        "/MyCoReWebPage/section/div[@id='mycore-acl-editor2']");
    Object node = xpath.evaluateFirst(webPage);
    MCRSession mcrSession = MCRSessionMgr.getCurrentSession();
    String lang = mcrSession.getCurrentLanguage();
    if (node != null) {
        Element mainDiv = (Element) node;
        mainDiv.setAttribute("lang", lang);
        String bsPath = CONFIG.getString("MCR.bootstrap.path", "");
        if (!bsPath.equals("")) {
            bsPath = MCRFrontendUtil.getBaseURL() + bsPath;
            Element item = new Element("link").setAttribute("href", bsPath).setAttribute("rel", "stylesheet")
                .setAttribute("type", "text/css");
            mainDiv.addContent(0, item);
        }
    }
    MCRContent content = MCRJerseyUtil.transform(webPage, request);
    return content.getInputStream();
}
 
开发者ID:MyCoRe-Org,项目名称:mycore,代码行数:27,代码来源:MCRAclEditorResource.java

示例13: generateValidMyCoReObject

import org.jdom2.xpath.XPathFactory; //导入依赖的package包/类
/**
 * tries to generate a valid MCRObject as JDOM Document.
 * 
 * @return MCRObject
 */
public Document generateValidMyCoReObject() throws JDOMException, SAXParseException, IOException {
    MCRObject obj;
    // load the JDOM object
    XPathFactory.instance()
        .compile("/mycoreobject/*/*/*/@editor.output", Filters.attribute())
        .evaluate(input)
        .forEach(Attribute::detach);
    try {
        byte[] xml = new MCRJDOMContent(input).asByteArray();
        obj = new MCRObject(xml, true);
    } catch (SAXParseException e) {
        XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat());
        LOGGER.warn("Failure while parsing document:\n{}", xout.outputString(input));
        throw e;
    }
    Date curTime = new Date();
    obj.getService().setDate("modifydate", curTime);

    // return the XML tree
    input = obj.createXML();
    return input;
}
 
开发者ID:MyCoRe-Org,项目名称:mycore,代码行数:28,代码来源:MCREditorOutValidator.java

示例14: singleTransform

import org.jdom2.xpath.XPathFactory; //导入依赖的package包/类
@Test
public void singleTransform()
    throws JDOMException, IOException, TransformerFactoryConfigurationError, TransformerException {
    String testFilePath = "/" + getClass().getSimpleName() + "/oneObj.xml";
    InputStream testXMLAsStream = getClass().getResourceAsStream(testFilePath);

    JDOMResult jdomResult = xslTransformation(testXMLAsStream);

    Document resultXML = jdomResult.getDocument();

    //        XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat());
    //        xmlOutputter.output(resultXML, System.out);

    List<Element> mycoreojectTags = XPathFactory.instance()
        .compile("/solr-document-container/source/mycoreobject", Filters.element()).evaluate(resultXML);
    assertEquals(1, mycoreojectTags.size());

    List<Element> userFieldTags = XPathFactory.instance()
        .compile("/solr-document-container/source/user", Filters.element()).evaluate(resultXML);
    assertEquals(1, userFieldTags.size());
}
 
开发者ID:MyCoRe-Org,项目名称:mycore,代码行数:22,代码来源:MCRMycoreObjectSolrXSLTest.java

示例15: multiTransform

import org.jdom2.xpath.XPathFactory; //导入依赖的package包/类
@Test
public void multiTransform()
    throws JDOMException, IOException, TransformerFactoryConfigurationError, TransformerException {
    String testFilePath = "/" + getClass().getSimpleName() + "/multiplObj.xml";
    InputStream testXMLAsStream = getClass().getResourceAsStream(testFilePath);

    JDOMResult jdomResult = xslTransformation(testXMLAsStream);

    Document resultXML = jdomResult.getDocument();

    //        XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat());
    //        xmlOutputter.output(resultXML, System.out);

    List<Element> mycoreojectTags = XPathFactory.instance()
        .compile("/solr-document-container/source/mycoreobject", Filters.element()).evaluate(resultXML);
    assertEquals(3, mycoreojectTags.size());

    List<Element> userFieldTags = XPathFactory.instance()
        .compile("/solr-document-container/source/user", Filters.element()).evaluate(resultXML);
    assertEquals(3, userFieldTags.size());
}
 
开发者ID:MyCoRe-Org,项目名称:mycore,代码行数:22,代码来源:MCRMycoreObjectSolrXSLTest.java


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