Java 类org.jdom2.xpath.XPathFactory 实例源码

项目:bibliometrics    文件:ScopusConnector.java   
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;
}
项目:bibliometrics    文件:ScopusConnector.java   
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;
}
项目:atf-toolbox-java    文件:XMLDataDriver.java   
@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;
}
项目:mycore    文件:MCRBinding.java   
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());
    }
}
项目:mycore    文件:MCRMODSLinkedMetadataTest.java   
@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());
}
项目:mycore    文件:MCRMetsIIIFModsMetadataExtractor.java   
@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());
}
项目:mycore    文件:MCRMetsSave.java   
/**
 * 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;
}
项目:mycore    文件:MCRSimpleModelXMLConverterTest.java   
@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);
        });
}
项目:mycore    文件:MCRURNObjectXPathMetadataManager.java   
@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);
}
项目:mycore    文件:MCRRestAPIClassifications.java   
/**
 * 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();
}
项目:mycore    文件:MCRRestAPIObjectsHelper.java   
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
            }

        }
    }
}
项目:mycore    文件:MCRAclEditorResource.java   
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();
}
项目:mycore    文件:MCREditorOutValidator.java   
/**
 * 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;
}
项目:mycore    文件:MCRMycoreObjectSolrXSLTest.java   
@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());
}
项目:mycore    文件:MCRMycoreObjectSolrXSLTest.java   
@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());
}
项目:mycore    文件:MCRMycoreObjectSolrXSLTest.java   
@Test
public void derivates()
    throws JDOMException, IOException, TransformerFactoryConfigurationError, TransformerException {
    String testFilePath = "/" + getClass().getSimpleName() + "/xml/derivateObj.xml";
    InputStream testXMLAsStream = getClass().getResourceAsStream(testFilePath);

    //        JDOMResult jdomResult = xslTransformation(testXMLAsStream, "/" + getClass().getSimpleName() + "/xsl/mcr2solrOld.xsl");
    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/mycorederivate", Filters.element()).evaluate(resultXML);
    assertEquals(1, mycoreojectTags.size());
}
项目:contestparser    文件:HolidayEndpoint.java   
@Autowired
public HolidayEndpoint(HumanResourceService humanResourceService)
        throws JDOMException, XPathFactoryConfigurationException,
        XPathExpressionException {
    this.humanResourceService = humanResourceService;

    Namespace namespace = Namespace.getNamespace("hr", NAMESPACE_URI);

    XPathFactory xPathFactory = XPathFactory.instance();

    this.startDateExpression = xPathFactory.compile("//hr:StartDate",
            Filters.element(), null, namespace);
    this.endDateExpression = xPathFactory.compile("//hr:EndDate", Filters.element(),
            null, namespace);
    this.nameExpression = xPathFactory.compile(
            "concat(//hr:FirstName,' ',//hr:LastName)", Filters.fstring(), null,
            namespace);
}
项目:DeadReckoning    文件:CarPark.java   
private static String getName(Document doc) {

        XPathFactory xFactory = XPathFactory.instance();
        XPathExpression<Attribute> exprAttribute = xFactory.compile(
                "/osm/relation" + "[member]" + "[tag/@k='name' and tag/@v]"
                        + "[tag/@k='type' and tag/@v='site']"
                        + "[tag/@k='site' and tag/@v='parking']"
                        + "/tag[@k='name']/@v", Filters.attribute());
        Attribute nameAttribute = exprAttribute.evaluateFirst(doc);
        if (nameAttribute == null) {
            exprAttribute = xFactory
                    .compile(
                            "/osm/way[tag/@k='amenity' and tag/@v='parking']/tag[@k='name']/@v",
                            Filters.attribute());
            nameAttribute = exprAttribute.evaluateFirst(doc);
        }
        String name = nameAttribute.getValue();
        return name;

    }
项目:DeadReckoning    文件:CarPark.java   
private static Map<Integer, GeoNode> getNodes(Document doc) {
    Map<Integer, GeoNode> nList = new HashMap<Integer, GeoNode>();

    XPathFactory xFactory = XPathFactory.instance();
    XPathExpression<Element> exprElement = xFactory.compile(
            "/osm/node[@id and @lat and @lon]", Filters.element());
    List<Element> nodesEle = exprElement.evaluate(doc);
    for (Element nele : nodesEle) {

        GeoNode n = null;
        try {
            int id = nele.getAttribute("id").getIntValue();
            double lat = nele.getAttribute("lat").getDoubleValue();
            double lon = nele.getAttribute("lon").getDoubleValue();
            n = new GeoNode(id, lat, lon, 0);
        } catch (DataConversionException e) {
            e.printStackTrace();
        }
        nList.put(n.id, n);
    }

    return nList;
}
项目:DeadReckoning    文件:CarParkGraph.java   
public static Map<Integer, GeoNode> getNodes(Document doc) {
    Map<Integer, GeoNode> nList = new HashMap<Integer, GeoNode>();

    XPathFactory xFactory = XPathFactory.instance();
    XPathExpression<Element> exprElement = xFactory.compile(
            "/osm/node[@id and @lat and @lon]", Filters.element());
    List<Element> nodesEle = exprElement.evaluate(doc);
    for (Element nele : nodesEle) {

        GeoNode n = null;
        try {
            int id = nele.getAttribute("id").getIntValue();
            double lat = nele.getAttribute("lat").getDoubleValue();
            double lon = nele.getAttribute("lon").getDoubleValue();
            n = new GeoNode(id, lat, lon, 0);
        } catch (DataConversionException e) {
            e.printStackTrace();
        }
        nList.put(n.id, n);
    }

    return nList;
}
项目:DeadReckoning    文件:Reader.java   
public Reader(File file, String name) {
    SAXBuilder builder = new SAXBuilder();
    try {

        doc = (Document) builder.build(file);
        Element root = doc.getRootElement();

        // use the default implementation
        XPathFactory xFactory = XPathFactory.instance();
        // System.out.println(xFactory.getClass());

        // select all data for motion sensor
        XPathExpression<Element> expr = xFactory.compile(
                "/SensorData/data[@" + Data.NAMETAG + "='" + name + "']",
                Filters.element());

        it = expr.evaluate(doc).iterator();

    } catch (IOException io) {
        System.out.println(io.getMessage());
    } catch (JDOMException jdomex) {
        System.out.println(jdomex.getMessage());
    }
}
项目:DeadReckoning    文件:Reader.java   
public Reader(File file) {
    SAXBuilder builder = new SAXBuilder();
    try {

        doc = (Document) builder.build(file);
        Element root = doc.getRootElement();

        // use the default implementation
        XPathFactory xFactory = XPathFactory.instance();
        // System.out.println(xFactory.getClass());

        // select all data for motion sensor
        XPathExpression<Element> expr = xFactory.compile(
                "/SensorData/data", Filters.element());

        it = expr.evaluate(doc).iterator();

    } catch (IOException io) {
        System.out.println(io.getMessage());
    } catch (JDOMException jdomex) {
        System.out.println(jdomex.getMessage());
    }
}
项目:wot_gateways    文件:DatapointLocator.java   
/**
 * List all datapoints of a functionality
 * 
 * @param p_functionality
 *            The name of the group to perform the action on. For example in
 *            the url kitchen_light.ground.home.com the functionality would
 *            be kitchen_light
 * @param p_location
 *            The middle dns name of the url without the top level domain.
 *            For example in the url kitchen_light.ground.home.com the
 *            location would be ground.home
 * @return An ArrayList of datapoints descriptions
 */
public ArrayList<DatapointDescription> listDatapoints(
        String p_functionality, String p_location) {
    ArrayList<DatapointDescription> l_dps = new ArrayList<DatapointDescription>();
    // Create the xpath expression to find the datapoint
    XPathExpression<Element> l_xpath = XPathFactory
            .instance()
            .compile(
                    "/datapoints/datapoint[lower-case(@location)='"
                            + p_location.toLowerCase()
                            + "' and translate(lower-case(@name), 'àäâéèêëüûùôöò', 'aaaeeeeuuuooo')='"
                            + p_functionality.toLowerCase() + "']",
                    Filters.element());
    List<Element> l_elements = l_xpath.evaluate(m_Document);
    for (int i = 0; i < l_elements.size(); i++) {
        l_dps.add(new DatapointDescription(l_elements.get(i)
                .getAttributeValue("actionName"), l_elements.get(i)
                .getAttributeValue("dptID"), l_elements.get(i)
                .getAttributeValue("actionDesc"), l_elements.get(i)
                .getAttributeValue("dptDesc"), Integer.parseInt(l_elements
                .get(i).getAttributeValue("dptBitsSize"))));
    }

    return l_dps;
}
项目:bluima    文件:UscTteCollectionReader.java   
@Override
public void initialize(UimaContext context)
        throws ResourceInitializationException {
    inputDir = CORPORA_BASE + "USC_TTE_corpus";
    // inputDir = CORPORA_HOME + "src/test/resources/corpus/USC_TTE_corpus";
    docCnt = 1;
    super.initialize(context);
    try {
        File corpusDir = new File(inputDir);
        checkArgument(corpusDir.exists());
        // duplicating code from AbstractFileReader to add "xml" filtering
        fileIterator = DirectoryIterator.get(directoryIterator, corpusDir,
                "xml", false);
        builder = new SAXBuilder();
        xo = new XMLOutputter();
        xo.setFormat(Format.getRawFormat());
        sentenceXPath = XPathFactory.instance().compile("//S");
    } catch (Exception e) {
        throw new ResourceInitializationException(
                ResourceInitializationException.NO_RESOURCE_FOR_PARAMETERS,
                new Object[] { inputDir });
    }
}
项目:marmotta    文件:XPathFunction.java   
private LinkedList<String> doFilter(String in, Set<String> xpaths) throws IOException {
    LinkedList<String> result = new LinkedList<String>();
    try {
        Document doc = new SAXBuilder(XMLReaders.NONVALIDATING).build(new StringReader(in));
        XMLOutputter out = new XMLOutputter();

        for (String xp : xpaths) {
            XPathExpression<Content> xpath = XPathFactory.instance().compile(xp, Filters.content());
            for (Content node : xpath.evaluate(doc)) {
                if(node instanceof Element) {
                    result.add(out.outputString((Element) node));
                } else if(node instanceof Text) {
                    result.add(out.outputString((Text) node));
                }
            }
        }
        return result;
    } catch (JDOMException xpe) {
        throw new IllegalArgumentException("error while processing xpath expressions: '" + xpaths + "'", xpe);
    }
}
项目:qpp-conversion-tool    文件:QualityMeasureIdDecoder.java   
/**
 * Obtains the measure GUID.
 *
 * @param element XML element that represents the Quality Measure Identifier
 * @return The measure GUID in the Quality Measure Identifier
 */
private List<String> getMeasureGuid(final Element element) {
    String expressionStr = getXpath(MEASURE_ID);

    XPathExpression<Attribute> expression = XPathFactory.instance()
        .compile(expressionStr, Filters.attribute(), null, xpathNs);
    return expression.evaluate(element).stream()
        .map(Attribute::getValue)
        .collect(Collectors.toList());
}
项目:qpp-conversion-tool    文件:XmlInputDecoder.java   
/**
 * Executes an Xpath for an element and executes the consumer
 *
 * @param element Element the xpath is executed against
 * @param expressionStr Xpath
 * @param consumer Consumer to execute if the xpath matches
 * @param filter Filter to apply for the xpath
 * @param selectOne Whether to execute for the first match or multiple matches
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
void setOnNode(Element element, String expressionStr,
                Consumer consumer, Filter<?> filter, boolean selectOne) {
    XPathExpression<?> expression = XPathFactory.instance().compile(expressionStr, filter, null,  xpathNs);

    if (selectOne) {
        Optional.ofNullable(expression.evaluateFirst(element)).ifPresent(consumer);
    } else {
        List<?> elems = expression.evaluate(element);
        Optional.ofNullable(elems)
                .ifPresent(notNullElems -> notNullElems.forEach(consumer));
    }
}
项目:sumo    文件:SumoSafeReader.java   
public SumoSafeReader(String safePath) throws JDOMException, IOException,
        JAXBException {
    SAXBuilder builder = new SAXBuilder();
    safe = builder.build(new File(safePath));
    xFactory = XPathFactory.instance();
    this.safePath = safePath;
}
项目:bibliometrics    文件:InstitutionBuilder.java   
private static void addDataFromScopusProfile(Element profile, String type, Institution institution) {
    XPathExpression<Element> xPathInstitution;
    XPathExpression<Element> xPathDepartment;
    XPathExpression<Element> xPathAdress;
    if (type.equals("short")) {
        xPathInstitution = XPathFactory.instance().compile(pathToInstitutionInAuthorProfile, Filters.element());
        xPathDepartment = XPathFactory.instance().compile(pathToDepartmentInAuthorProfile, Filters.element());
        xPathAdress = XPathFactory.instance().compile(pathToAddressInAuthorProfile, Filters.element());
    } else {
        xPathInstitution = XPathFactory.instance().compile(pathToInstitutionInAffilResponse, Filters.element());
        xPathDepartment = XPathFactory.instance().compile(pathToDepartmentnAffilResponse, Filters.element());
        xPathAdress = XPathFactory.instance().compile(pathToAddressnAffilResponse, Filters.element());
    }
    Element institutionElement = xPathInstitution.evaluateFirst(profile);
    Element departmentElement = xPathDepartment.evaluateFirst(profile);

    if (institutionElement != null) {
        institution.setDepartment(departmentElement.getText());
        institution.setInstitution(institutionElement.getText());
    } else if (departmentElement != null) {
        institution.setInstitution(departmentElement.getText());
    }

    Element addressElement = xPathAdress.evaluateFirst(profile);
    institution.setCity(addressElement.getChildText("city"));
    institution.setCountry(addressElement.getChildText("country"));
    if (profile.getChild("geoCoordinates") != null) {
        XPathExpression<Element> xPathLatitude = XPathFactory.instance().compile(pathToLatitude, Filters.element());
        XPathExpression<Element> xPathLongitude = XPathFactory.instance().compile(pathToLongitude, Filters.element());
        String textLatitude = xPathLatitude.evaluateFirst(profile).getText();
        String textLongitude = xPathLongitude.evaluateFirst(profile).getText();
        institution.setLatitude(Double.parseDouble(textLatitude));
        institution.setLongitude(Double.parseDouble(textLongitude));
    }
}
项目:bibliometrics    文件:CitationStatistics.java   
public CitationStatistics(Set<Element> mcrEntries, String source) throws HttpException, IOException, JDOMException, SAXException {
    this.source = source;
    totalCitations = 0;
    uncited = 0;
    numberOfDocumentsWithCitationData = 0;
    hIndex = 0;        

    List<Namespace> namespaces = MCRConstants.getStandardNamespaces();
    namespaces.add(DC_Namespace);
    namespaces.add(ELSEVIER_Namespace);
    List<Integer> citationCounts = new ArrayList<>();

    for (Element mcrEntry : mcrEntries) {
        LOGGER.info(mcrEntry);
        XPathExpression<Element> xPath = XPathFactory.instance().compile(sourceIDScopus, Filters.element(),null, namespaces);
        Element idenitiferElement = xPath.evaluateFirst(mcrEntry);
        if (idenitiferElement != null) {
        String scopusID = xPath.evaluateFirst(mcrEntry).getValue();
        if (scopusID.contains("SCOPUS_ID:"))
            scopusID = scopusID.replace("SCOPUS_ID:", "");
        CitationGetter getter = new ScopusConnector();
        Element citationInformation = getter.getCitationInformation(scopusID);
        if (citationInformation != null) {
            mcrEntry.addContent(citationInformation);
            int numberOfCitations = Integer.parseInt(citationInformation.getChildText("count"));
            citationCounts.add(numberOfCitations);
            LOGGER.info("retrieved citation count " + numberOfCitations + " for document with scopus id " + scopusID);
            if (numberOfCitations == 0)
                uncited++;
            totalCitations += numberOfCitations;
            numberOfDocumentsWithCitationData++;
        }
        }

    }
    hIndex = calculateHIndex(citationCounts);
}
项目:bibliometrics    文件:MyCoReConnector.java   
public Element getPublicationByID(String id) throws IOException, JDOMException, SAXException {
    //build API URL
    String queryURL = API_URL + "objects/" + id;
    String pathToMODS = "metadata/def.modsContainer/modsContainer/mods:mods";
    XPathExpression<Element> xPath = XPathFactory.instance().compile(pathToMODS, Filters.element(),null,MCRConstants.getStandardNamespaces());
    return xPath.evaluateFirst(getResponse(queryURL).asXML().detachRootElement().clone());
}
项目:bibliometrics    文件:MyCoReConnector.java   
private List<String> getMCRIDs(PublicationAuthor author) throws IOException, JDOMException, SAXException {
    //prepare list of results blocks 
    String query = prepareAuthorQuery(author);

    //divide API request in blocks a 100 documents 
    int numberOfPublications = getNumberOfPublications(query);

    String pathToID = "result/doc/str[@name='id']";
   // String pathToID = "lst[@name='responseHeader']";

    XPathExpression<Element> xPath = XPathFactory.instance().compile(pathToID, Filters.element());

    List<String> foundMCRIds = new ArrayList<>();
    //at the moment only testing, two blocks a 10 documents
    for (int i = 0; i < ( (numberOfPublications / 100) + 1); i++) {
        int start = 100 * i;
                    //build API URL
        String queryURL = query + "&rows=100&start=" + start;
        Element response = getResponse(queryURL).asXML().detachRootElement().clone();

        List<Element> foundMCRIDElements = xPath.evaluate(response);
        LOGGER.info("found " + foundMCRIDElements.size() + " mods elements");
        for (Element mcrIDElement : foundMCRIDElements) {
            String mcrID = mcrIDElement.getValue();
            if (!mcrID.contains("-"))
                foundMCRIds.add(mcrID);
        }
    }
    LOGGER.info("retrieved " + foundMCRIds.size() + " entries from MyCoRe repository.");
    //return API-response
    return foundMCRIds;
}
项目:bibliometrics    文件:GoogleMapsConnector.java   
public Element getGeoData(String location) throws JDOMException, HttpException, IOException, SAXException {
    //build API URL
    String queryURL = API_URL + "?address="+ urlEncode(location.replace(" ", "+")) + "&key="+ API_KEY;
    LOGGER.info("Retrieving coordinates for " + location);

    Element response = getResponse(queryURL).asXML().detachRootElement().clone();

    XPathExpression<Element> xPathGeoData = XPathFactory.instance().compile(pathToGeoData,
Filters.element());

    Element geodata = xPathGeoData.evaluateFirst(response);
    return geodata;
}
项目:bibliometrics    文件:ScopusConnector.java   
public int getNumberOfPublications(PublicationAuthor author)
        throws JDOMException, IOException, SAXException {
    if (!author.getScopusAuthorID().isEmpty()) {
        String queryURL = API_URL + "/author/AUTHOR_ID:" + author.getScopusAuthorID()
                + "?start=0&count=200&view=DOCUMENTS&apikey=" + API_KEY;
        XPathExpression<Element> xPath = XPathFactory.instance().compile(pathToNumber, Filters.element());
        Element numberElement = xPath.evaluateFirst(getResponse(queryURL).asXML().detachRootElement().clone());

        // read and return total number of publications from the Element
        return Integer.parseInt(numberElement.getValue());
    } else
        return 0;
}
项目:bibliometrics    文件:ScopusConnector.java   
public int getCitationCount(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> xPath = XPathFactory.instance().compile(pathToCitationCount, Filters.element());
    Element citationCountElement = xPath.evaluateFirst(getResponse(queryURL).asXML());
    return Integer.parseInt(citationCountElement.getValue());
}
项目:goobi-viewer-indexer    文件:JDomXP.java   
@SuppressWarnings({ "rawtypes", "unchecked" })
public static List<Object> evaluate(String expr, Object parent, Filter filter) throws FatalIndexerException {
    XPathBuilder<Object> builder = new XPathBuilder<>(expr.trim().replace("\n", ""), filter);
    // Add all namespaces
    for (String key : Configuration.getInstance().getNamespaces().keySet()) {
        Namespace value = Configuration.getInstance().getNamespaces().get(key);
        builder.setNamespace(key, value.getURI());
    }
    XPathExpression<Object> xpath = builder.compileWith(XPathFactory.instance());
    return xpath.evaluate(parent);

}
项目:mycore    文件:MCRClassificationMappingEventHandler.java   
private void createMapping(MCRObject obj) {
    MCRMetaElement mappings = obj.getMetadata().getMetadataElement("mappings");
    if (mappings != null) {
        oldMappings = mappings.clone();
        obj.getMetadata().removeMetadataElement("mappings");
    }

    Element currentClassElement = null;
    try {
        Document doc = new Document(obj.getMetadata().createXML().detach());
        XPathExpression<Element> classElementPath = XPathFactory.instance().compile("//*[@categid]",
            Filters.element());
        List<Element> classList = classElementPath.evaluate(doc);
        if (classList.size() > 0) {
            mappings = new MCRMetaElement();
            mappings.setTag("mappings");
            mappings.setClass(MCRMetaClassification.class);
            mappings.setHeritable(false);
            mappings.setNotInherit(true);
            obj.getMetadata().setMetadataElement(mappings);
        }
        for (Element classElement : classList) {
            currentClassElement = classElement;
            MCRCategory categ = DAO.getCategory(new MCRCategoryID(classElement.getAttributeValue("classid"),
                classElement.getAttributeValue("categid")), 0);
            addMappings(mappings, categ);
        }
    } catch (Exception je) {
        if (currentClassElement == null) {
            LOGGER.error("Error while finding classification elements", je);
        } else {
            LOGGER.error("Error while finding classification elements for {}",
                new XMLOutputter().outputString(currentClassElement), je);
        }
    } finally {
        if (mappings == null || mappings.size() == 0) {
            obj.getMetadata().removeMetadataElement("mappings");
        }
    }
}
项目:mycore    文件:MCRXMLCleaner.java   
public MCRCleaningRule(String xPathExprNodesToInspect, String xPathExprRelevancyTest) {
    this.xPathExprNodesToInspect = xPathExprNodesToInspect;
    this.xPathNodesToInspect = XPathFactory.instance().compile(xPathExprNodesToInspect, Filters.fpassthrough(),
        null,
        MCRConstants.getStandardNamespaces());
    this.xPathRelevancyTest = XPathFactory.instance().compile(xPathExprRelevancyTest, Filters.fpassthrough(), null,
        MCRConstants.getStandardNamespaces());
}
项目:mycore    文件:MCRMODSWrapperTest.java   
/**
 * Test method for {@link org.mycore.mods.MCRMODSWrapper#wrapMODSDocument(org.jdom2.Element, java.lang.String)}.
 */
@Test
public void testWrapMODSDocument() throws SAXParseException, URISyntaxException, JDOMException, IOException {
    Document modsDoc = loadMODSDocument();
    MCRObject mcrObj = MCRMODSWrapper.wrapMODSDocument(modsDoc.getRootElement(), "JUnit");
    assertTrue("Generated MCRObject is not valid.", mcrObj.isValid());
    Document mcrObjXml = mcrObj.createXML();
    //check load from XML throws no exception
    MCRObject mcrObj2 = new MCRObject(mcrObjXml);
    mcrObjXml = mcrObj2.createXML();
    XPathExpression<Element> xpathCheck = XPathFactory.instance().compile("//mods:mods", Filters.element(), null,
        MCRConstants.MODS_NAMESPACE);
    assertEquals("Did not find mods data", 1, xpathCheck.evaluate(mcrObjXml).size());
}
项目:mycore    文件:MCRMODSWrapperTest.java   
@Test
public void testSetMODS() throws SAXParseException, IOException, JDOMException {
    Element mods = loadMODSDocument().detachRootElement();
    MCRMODSWrapper wrapper = new MCRMODSWrapper();
    wrapper.setID("JUnit", 4711);
    wrapper.setMODS(mods);
    Document mcrObjXml = wrapper.getMCRObject().createXML();
    XPathExpression<Element> xpathCheck = XPathFactory.instance().compile("//mods:mods", Filters.element(), null,
        MCRConstants.MODS_NAMESPACE);
    assertEquals("Did not find mods data", 1, xpathCheck.evaluate(mcrObjXml).size());
}