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


Java SAXBuilder类代码示例

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


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

示例1: getDocumentFromString

import org.jdom2.input.SAXBuilder; //导入依赖的package包/类
/**
 * Create a JDOM document from an XML string.
 * 
 * @param string
 * @param encoding
 * @return
 * @throws IOException
 * @throws JDOMException
 * @should build document correctly
 */
public static Document getDocumentFromString(String string, String encoding) throws JDOMException, IOException {
    if (encoding == null) {
        encoding = DEFAULT_ENCODING;
    }

    byte[] byteArray = null;
    try {
        byteArray = string.getBytes(encoding);
    } catch (UnsupportedEncodingException e) {
    }
    ByteArrayInputStream baos = new ByteArrayInputStream(byteArray);
    SAXBuilder builder = new SAXBuilder();
    Document document = builder.build(baos);

    return document;
}
 
开发者ID:intranda,项目名称:goobi-viewer-connector,代码行数:27,代码来源:Utils.java

示例2: getDocumentFromString

import org.jdom2.input.SAXBuilder; //导入依赖的package包/类
/**
 * Create a JDOM document from an XML string.
 *
 * @param string
 * @return
 * @throws IOException
 * @throws JDOMException
 * @should build document correctly
 */
public static Document getDocumentFromString(String string, String encoding) throws JDOMException, IOException {
    if (string == null) {
        throw new IllegalArgumentException("string may not be null");
    }
    if (encoding == null) {
        encoding = "UTF-8";
    }

    byte[] byteArray = null;
    try {
        byteArray = string.getBytes(encoding);
    } catch (UnsupportedEncodingException e) {
    }
    ByteArrayInputStream baos = new ByteArrayInputStream(byteArray);

    // Reader reader = new StringReader(hOCRText);
    SAXBuilder builder = new SAXBuilder();
    Document document = builder.build(baos);

    return document;
}
 
开发者ID:intranda,项目名称:goobi-viewer-indexer,代码行数:31,代码来源:Utils.java

示例3: parseXml

import org.jdom2.input.SAXBuilder; //导入依赖的package包/类
public void parseXml(String fileName){
	SAXBuilder builder = new SAXBuilder();
	File file = new File(fileName);
	try {
		Document document = (Document) builder.build(file);
		Element rootNode = document.getRootElement();
		List list = rootNode.getChildren("author");
		for (int i = 0; i < list.size(); i++) {
			Element node = (Element) list.get(i);
			System.out.println("First Name : " + node.getChildText("firstname"));
			System.out.println("Last Name : " + node.getChildText("lastname"));
		}
	} catch (IOException io) {
		System.out.println(io.getMessage());
	} catch (JDOMException jdomex) {
		System.out.println(jdomex.getMessage());
	}



}
 
开发者ID:PacktPublishing,项目名称:Java-Data-Science-Cookbook,代码行数:22,代码来源:TestJdom.java

示例4: doGetPost

import org.jdom2.input.SAXBuilder; //导入依赖的package包/类
public void doGetPost(MCRServletJob job) throws Exception {
    HttpServletRequest req = job.getRequest();
    String path = job.getRequest().getPathInfo().substring(1);
    LOGGER.info(path);
    boolean b = tryLogin(path.substring(0, 6), path.substring(6), false);
    if (b) {
        org.apache.shiro.subject.Subject currentUser = SecurityUtils.getSubject();
        if (currentUser.hasRole("client")) {
            String hash = req.getUserPrincipal().getName();
            File reportFile = new File(resultsDir + "/" + hash.substring(0, 6), "report.xml");
            SAXBuilder builder = new SAXBuilder();
            Document document = builder.build(reportFile);
            getLayoutService().doLayout(job.getRequest(), job.getResponse(), new MCRJDOMContent(document));
            }
    }
}
 
开发者ID:ETspielberg,项目名称:bibliometrics,代码行数:17,代码来源:BibliometricReportDisplayServlet.java

示例5: parse

import org.jdom2.input.SAXBuilder; //导入依赖的package包/类
private long parse(String fileName, String lang, ClamlClassProcessor processor) throws Exception {
	processor.reset();
	jobOutput.println("reading from file " + fileName);
	Element root = (new SAXBuilder()).build(new File(fileName)).getRootElement();
	parseClassKinds(root);
	parseModifiers(root);
	parseModifierClasses(root);
	parseClasses(root);
	long categoryClassCount = 0l;
	Iterator<String> kindsIt = classKinds.keySet().iterator();
	while (kindsIt.hasNext()) {
		String kind = kindsIt.next();
		Map<String, Element> codeMap = classKinds.get(kind);
		Iterator<String> codesIt = codeMap.keySet().iterator();
		while (codesIt.hasNext()) {
			String code = codesIt.next();
			categoryClassCount += processor.processClass(kind, code, codeMap.get(code), classKinds, modifierClasses, lang);
		}
	}
	jobOutput.println(categoryClassCount + " ClaML categories processed");
	processor.postProcess();
	return categoryClassCount;
}
 
开发者ID:phoenixctms,项目名称:ctsms,代码行数:24,代码来源:ClamlImporter.java

示例6: merge

import org.jdom2.input.SAXBuilder; //导入依赖的package包/类
/**
 * Merges a given XML file with a patch. This API is designed for CobiGen
 * @see com.github.maybeec.lexeme.LeXeMerger#merge(Element, Element, ConflictHandlingType)
 * @param base
 *            File
 * @param patch
 *            String
 * @param charSet
 *            target charset of the file to be read and write
 * @param conflictHandling
 *            {@link ConflictHandlingType} specifying how conflicts will be handled during the merge
 *            process. If null the default for this LeXeMerger will be used
 * @return Document the merged result of base and patch
 * @throws XMLMergeException
 *             when the Documents can't be properly merged
 * @author sholzer (23.04.2015)
 */
public Document merge(File base, String patch, String charSet, ConflictHandlingType conflictHandling)
    throws XMLMergeException {
    if (conflictHandling == null) {
        conflictHandling = conflictHandlingType;
    }
    try {
        SAXBuilder builder = new SAXBuilder(XMLReaders.NONVALIDATING);
        builder.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        String baseString = JDom2Util.getInstance().readFile(base.getPath(), charSet);
        Document baseDoc =
            builder.build(new InputSource(new BufferedReader(new StringReader(baseString))));
        Document patchDoc = builder.build(new InputSource(new BufferedReader(new StringReader(patch))));
        return merge(baseDoc, patchDoc, conflictHandling);
    } catch (IOException | JDOMException e) {
        logger.error("Caught unexcpected {}:{}", e.getClass().getName(), e.getMessage());
        throw new XMLMergeException(e.getMessage());
    }

}
 
开发者ID:maybeec,项目名称:lexeme,代码行数:37,代码来源:LeXeMerger.java

示例7: testAttributeOrdering

import org.jdom2.input.SAXBuilder; //导入依赖的package包/类
/**
 * Tests if the Attribute order is preserved while parsing
 *
 * @author sholzer (04.05.2015)
 * @throws IOException
 *             when file not found (i guess...)
 * @throws JDOMException
 *             when something else goes wrong
 */
@Test
public void testAttributeOrdering() throws JDOMException, IOException {

    String path = "src/test/resources/";
    String filePath = path + "ConceptTest.xml";
    SAXBuilder builder = new SAXBuilder();
    Document doc = builder.build(filePath);

    Element element = doc.getRootElement();
    List<org.jdom2.Attribute> attributes = element.getAttributes();
    System.out.println(attributes);
    assertTrue(attributes.toString(), attributes.get(0).getName().equals("b"));
    assertTrue(attributes.toString(), attributes.get(1).getName().equals("c"));
    assertTrue(attributes.toString(), attributes.get(2).getName().equals("a"));
}
 
开发者ID:maybeec,项目名称:lexeme,代码行数:25,代码来源:ElementMergerImplTest.java

示例8: getMonomerList

import org.jdom2.input.SAXBuilder; //导入依赖的package包/类
public static List<Monomer> getMonomerList(String monomerXMLString)
    throws JDOMException, IOException, MonomerException, CTKException, ChemistryException {
  List<Monomer> l = new ArrayList<Monomer>();
  if (null != monomerXMLString && monomerXMLString.length() > 0) {
    SAXBuilder builder = new SAXBuilder();
    ByteArrayInputStream bais = new ByteArrayInputStream(
        monomerXMLString.getBytes());
    Document doc = builder.build(bais);
    Element root = doc.getRootElement();

    List monomers = root.getChildren();
    Iterator it = monomers.iterator();
    while (it.hasNext()) {
      Element monomer = (Element) it.next();
      Monomer m = getMonomer(monomer);
      if (MonomerParser.validateMonomer(m)) {
        l.add(m);
      }
    }
  }
  return l;
}
 
开发者ID:PistoiaHELM,项目名称:HELM2NotationToolkit,代码行数:23,代码来源:MonomerParser.java

示例9: ConfigurationController

import org.jdom2.input.SAXBuilder; //导入依赖的package包/类
/**
 * Constructor that optionally loads the XML file.
 */
public ConfigurationController(boolean shouldLoadXML) {
	if (shouldLoadXML) {
		this.configurationPath = this.prefs.get("configurationPath", "Path to file '/Users/user/desktop/config.xml'");
		if (isCustomConfigurationPath() && canGetFile()) {
			try {
				SAXBuilder builder = new SAXBuilder();
				File xmlFile = new File(this.configurationPath);
				Document document = builder.build(xmlFile);
				this.root = document.getRootElement();
			} catch (Exception e) {
				LOGGER.error("", e);
			}
		}
	}
}
 
开发者ID:jamf,项目名称:HealthCheckUtility,代码行数:19,代码来源:ConfigurationController.java

示例10: parseObjectCount

import org.jdom2.input.SAXBuilder; //导入依赖的package包/类
/**
 * Method that counts the elements in a JSS and writes to the JSON string.
 */
public void parseObjectCount(String Object, String url, String username, String password, JSONBuilder jsonString){
    try {
        HTTPController api = new HTTPController(username, password);
        SAXBuilder sb = new SAXBuilder();
        String result = api.doGet(url + "/JSSResource/" + Object);
        Document doc = sb.build(new ByteArrayInputStream(result.getBytes("UTF-8")));
        List<Element> objects = doc.getRootElement().getChildren();
        int count = parseMultipleObjects(objects).size();

        jsonString.addObject(Object);
        jsonString.addFinalElement("count",Integer.toString(count));
        jsonString.closeObject();
    } catch (Exception e){
        e.printStackTrace();
        System.out.print(e);
    }

}
 
开发者ID:jamf,项目名称:HealthCheckUtility,代码行数:22,代码来源:HealthCheck.java

示例11: importObjectCLI

import org.jdom2.input.SAXBuilder; //导入依赖的package包/类
/**
 * Same as {@link #importObject(Path, String)} but returns a list of derivates which
 * should be imported afterwards.
 * 
 * @param targetDirectory
 *                the directory where the *.tar was unpacked
 * @param objectId
 *                object id to import
 * @throws JDOMException
 *                coulnd't parse the import order xml
 * @throws IOException
 *                when an I/O error prevents a document from being fully parsed
 * @throws MCRActiveLinkException
 *                if object is created (no real update), see {@link MCRMetadataManager#create(MCRObject)}
 * @throws MCRAccessException 
 *                if write permission is missing or see {@link MCRMetadataManager#create(MCRObject)}
 */
public static List<String> importObjectCLI(Path targetDirectory, String objectId)
    throws JDOMException, IOException, MCRActiveLinkException, MCRAccessException {
    SAXBuilder sax = new SAXBuilder();
    Path targetXML = targetDirectory.resolve(CONTENT_DIRECTORY).resolve(objectId + ".xml");
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(MessageFormat.format("Importing {0}", targetXML.toAbsolutePath().toString()));
    }
    Document objXML = sax.build(targetXML.toFile());
    MCRObject mcr = new MCRObject(objXML);
    mcr.setImportMode(true);

    List<String> derivates = new LinkedList<>();
    // one must copy the ids before updating the mcr objects
    for (MCRMetaLinkID id : mcr.getStructure().getDerivates()) {
        derivates.add(id.getXLinkHref());
    }
    // delete children & derivate -> will be added later
    mcr.getStructure().clearChildren();
    mcr.getStructure().clearDerivates();
    // update
    MCRMetadataManager.update(mcr);
    // return list of derivates
    return derivates;
}
 
开发者ID:MyCoRe-Org,项目名称:mycore,代码行数:42,代码来源:MCRTransferPackageUtil.java

示例12: accumulate

import org.jdom2.input.SAXBuilder; //导入依赖的package包/类
@Override
public void accumulate(SolrInputDocument document, Path filePath, BasicFileAttributes attributes)
    throws IOException {
    String parentPath = MCRPath.toMCRPath(filePath).getParent().getOwnerRelativePath();
    if (!"/alto".equals(parentPath)) {
        return;
    }
    try (InputStream is = Files.newInputStream(filePath)) {
        SAXBuilder builder = new SAXBuilder();
        Document altoDocument = builder.build(is);
        Element rootElement = altoDocument.getRootElement();
        extractWords(rootElement).forEach(value -> document.addField("alto_words", value));
        document.addField("alto_content", extractContent(rootElement));
    } catch (JDOMException e) {
        LogManager.getLogger().error("Unable to parse {}", filePath, e);
    }
}
 
开发者ID:MyCoRe-Org,项目名称:mycore,代码行数:18,代码来源:MCRSolrAltoExtractor.java

示例13: toJSON

import org.jdom2.input.SAXBuilder; //导入依赖的package包/类
@Test
public void toJSON() throws Exception {
    Map<String, String> properties = new HashMap<>();
    properties.put("MCR.WCMS2.mycoreTagList", "");
    MCRConfiguration.instance().initialize(properties, true);
    SAXBuilder builder = new SAXBuilder();
    Document doc = builder.build(new File("src/test/resources/navigation/content.xml"));
    MCRWCMSDefaultSectionProvider prov = new MCRWCMSDefaultSectionProvider();
    JsonArray sectionArray = prov.toJSON(doc.getRootElement());

    assertEquals(2, sectionArray.size());
    // test section one
    JsonObject section1 = (JsonObject) sectionArray.get(0);
    assertEquals("Title one", section1.getAsJsonPrimitive("title").getAsString());
    assertEquals("de", section1.getAsJsonPrimitive("lang").getAsString());
    assertEquals("<div><p>Content one</p><br /></div>", section1.getAsJsonPrimitive("data").getAsString());
    // test section two
    JsonObject section2 = (JsonObject) sectionArray.get(1);
    assertEquals("Title two", section2.getAsJsonPrimitive("title").getAsString());
    assertEquals("en", section2.getAsJsonPrimitive("lang").getAsString());
    assertEquals("Content two", section2.getAsJsonPrimitive("data").getAsString());
}
 
开发者ID:MyCoRe-Org,项目名称:mycore,代码行数:23,代码来源:JSONSectionProviderTest.java

示例14: transform

import org.jdom2.input.SAXBuilder; //导入依赖的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

示例15: addSection

import org.jdom2.input.SAXBuilder; //导入依赖的package包/类
/**
 * Adds a section to the MyCoRe webpage.
 * 
 * @param title the title of the section
 * @param xmlAsString xml string which is added to the section
 * @param lang the language of the section specified by a language key.
 * @return added section
 */
public Element addSection(String title, String xmlAsString, String lang) throws IOException, SAXParseException,
    JDOMException {
    String sb = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
        + "<!DOCTYPE MyCoReWebPage PUBLIC \"-//MYCORE//DTD MYCOREWEBPAGE 1.0//DE\" "
        + "\"http://www.mycore.org/mycorewebpage.dtd\">" + "<MyCoReWebPage>" + xmlAsString + "</MyCoReWebPage>";
    SAXBuilder saxBuilder = new SAXBuilder();
    saxBuilder.setEntityResolver((publicId, systemId) -> {
        String resource = systemId.substring(systemId.lastIndexOf("/"));
        InputStream is = getClass().getResourceAsStream(resource);
        if (is == null) {
            throw new IOException(new FileNotFoundException("Unable to locate resource " + resource));
        }
        return new InputSource(is);
    });
    StringReader reader = new StringReader(sb);
    Document doc = saxBuilder.build(reader);
    return this.addSection(title, doc.getRootElement().cloneContent(), lang);
}
 
开发者ID:MyCoRe-Org,项目名称:mycore,代码行数:27,代码来源:MyCoReWebPageProvider.java


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