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


Java Format类代码示例

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


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

示例1: sloppyPrint

import org.jdom2.output.Format; //导入依赖的package包/类
/**
 * Creates an outputter and writes an XML tree.
 *
 * The encoding argument here only sets an attribute in the
 * XML declaration. It's up to the caller to ensure the writer
 * is encoding bytes to match. If encoding is null, the default
 * is "UTF-8".
 *
 * If XML character entity escaping is allowed, otherwise unmappable
 * characters may be written without errors. If disabled, an
 * UnmappableCharacterException will make their presence obvious and fatal.
 *
 * LineEndings will be CR-LF. Except for comments!?
 *
 * @param doc
 * @param writer
 * @param disableEscaping
 */
public static void sloppyPrint( Document doc, Writer writer, String encoding, boolean allowEscaping ) throws IOException {
	Format format = Format.getPrettyFormat();
	format.setTextMode( Format.TextMode.PRESERVE );  // Permit leading/trailing space.
	format.setExpandEmptyElements( false );
	format.setOmitDeclaration( false );
	format.setIndent( "\t" );
	format.setLineSeparator( LineSeparator.CRNL );

	if ( encoding != null ) {
		format.setEncoding( encoding );
	}

	if ( !allowEscaping ) {
		format.setEscapeStrategy(new EscapeStrategy() {
			@Override
			public boolean shouldEscape( char ch ) {
				return false;
			}
		});
	}

	XMLOutputter outputter = new XMLOutputter( format, new SloppyXMLOutputProcessor() );
	outputter.output( doc, writer );
}
 
开发者ID:Vhati,项目名称:Slipstream-Mod-Manager,代码行数:43,代码来源:SloppyXMLOutputProcessor.java

示例2: exportXML

import org.jdom2.output.Format; //导入依赖的package包/类
public void exportXML(ArrayList<Pokemon> pokemons,String tipo){
    try {
	Element pokemon = new Element("pokemon");
    Document doc = new Document(pokemon);
    
    for(Pokemon p:pokemons) {
    	Element poke = new Element("pokemon");
    	poke.addContent(new Element("nombre").setText(p.getName()));
    	poke.addContent(new Element("peso").setText(String.valueOf(p.getWeight())));
    	poke.addContent(new Element("altura").setText(String.valueOf(p.getHeight())));
    	poke.addContent(new Element("base_experience").setText(String.valueOf(p.getBaseExperience())));
    	doc.getRootElement().addContent(poke);
    }
    XMLOutputter output = new XMLOutputter();
    output.setFormat(Format.getPrettyFormat());
    output.output(doc, new FileWriter("pokemons-tipo-"+tipo+".xml"));
    }catch(Exception e) {
    	System.out.println("Ocurri� alg�n error");
    }
}
 
开发者ID:mistermboy,项目名称:PokemonXMLFilter,代码行数:21,代码来源:XMLWriter.java

示例3: getStringFromElement

import org.jdom2.output.Format; //导入依赖的package包/类
/**
 * 
 * @param element
 * @param encoding
 * @return
 */
public static String getStringFromElement(Element element, String encoding) {
    if (element == null) {
        throw new IllegalArgumentException("element may not be null");
    }
    if (encoding == null) {
        encoding = DEFAULT_ENCODING;
    }
    Format format = Format.getRawFormat();
    XMLOutputter outputter = new XMLOutputter(format);
    Format xmlFormat = outputter.getFormat();
    if (StringUtils.isNotEmpty(encoding)) {
        xmlFormat.setEncoding(encoding);
    }
    xmlFormat.setExpandEmptyElements(true);
    outputter.setFormat(xmlFormat);
    String docString = outputter.outputString(element);

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

示例4: writeMuleXmlFile

import org.jdom2.output.Format; //导入依赖的package包/类
private void writeMuleXmlFile(Element element, VirtualFile muleConfig) {

        XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat());
        InputStream inputStream = null;
        try {
            String outputString = xout.outputString(element);
            logger.debug("*** OUTPUT STRING IS " + outputString);
            OutputStreamWriter writer = new OutputStreamWriter(muleConfig.getOutputStream(this));
            writer.write(outputString);
            writer.flush();
            writer.close();
        } catch (Exception e) {
            logger.error("Unable to write file: " + e);
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(inputStream);
        }
    }
 
开发者ID:machaval,项目名称:mule-intellij-plugins,代码行数:19,代码来源:SOAPKitScaffoldingAction.java

示例5: updateXMLValue

import org.jdom2.output.Format; //导入依赖的package包/类
/**
 * This method updates XML values from the Health Check GUI.
 * Not all items are supported. If it can't find the XML file,
 * it will print the error message. Could cause errors if the structure
 * of the XML file has been modified.
 */
public void updateXMLValue(String item, String value) {
	if (item.equals("jss_url")){
		this.root.getChildren().get(0).setText(value);
	} else if (item.equals("jss_username")){
		this.root.getChildren().get(1).setText(value);
	} else if (item.equals("jss_password")){
		this.root.getChildren().get(2).setText(value);
	} else if (item.equals("smart_groups")){
		this.root.getChildren().get(5).getChildren().get(1).setText(value);
	} else if (item.equals("extension_attributes")){
		this.root.getChildren().get(5).getChildren().get(2).getChildren().get(0).setText(value);
		this.root.getChildren().get(5).getChildren().get(2).getChildren().get(1).setText(value);
	}
	
	try {
		XMLOutputter o = new XMLOutputter();
		o.setFormat(Format.getPrettyFormat());
		o.output(this.root, new FileWriter(getConfigurationPath()));
	} catch (Exception e) {
		LOGGER.error("Unable to update XML file.", e);
	}
	
}
 
开发者ID:jamf,项目名称:HealthCheckUtility,代码行数:30,代码来源:ConfigurationController.java

示例6: doGetPost

import org.jdom2.output.Format; //导入依赖的package包/类
@Override
protected void doGetPost(MCRServletJob job) throws Exception {
    HttpServletRequest request = job.getRequest();
    // get base url
    if (this.myBaseURL == null) {
        this.myBaseURL = MCRFrontendUtil.getBaseURL() + request.getServletPath().substring(1);
    }
    logRequest(request);
    // create new oai request
    OAIRequest oaiRequest = new OAIRequest(fixParameterMap(request.getParameterMap()));
    // create new oai provider
    OAIXMLProvider oaiProvider = new JAXBOAIProvider(getOAIAdapter());
    // handle request
    OAIResponse oaiResponse = oaiProvider.handleRequest(oaiRequest);
    // build response
    Element xmlRespone = oaiResponse.toXML();
    // fire
    job.getResponse().setContentType("text/xml; charset=UTF-8");
    XMLOutputter xout = new XMLOutputter();
    xout.setFormat(Format.getPrettyFormat().setEncoding("UTF-8"));
    xout.output(addXSLStyle(new Document(xmlRespone)), job.getResponse().getOutputStream());
}
 
开发者ID:MyCoRe-Org,项目名称:mycore,代码行数:23,代码来源:MCROAIDataProvider.java

示例7: getEpicurLite

import org.jdom2.output.Format; //导入依赖的package包/类
@Override
public EpicurLite getEpicurLite(MCRURN urn) {
    EpicurLite elp = new EpicurLite(urn);
    URL url = null;
    // the base urn
    if (urn.getPath() == null || urn.getPath().trim().length() == 0) {
        elp.setFrontpage(true);
    }
    url = getURL(urn);
    elp.setUrl(url);
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Generated Epicur Lite for urn {} is \n{}", urn,
            new XMLOutputter(Format.getPrettyFormat()).outputString(elp.getEpicurLite()));
    }
    return elp;
}
 
开发者ID:MyCoRe-Org,项目名称:mycore,代码行数:17,代码来源:BaseEpicurLiteProvider.java

示例8: testUpdate

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

示例9: testToXML

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

示例10: toXML

import org.jdom2.output.Format; //导入依赖的package包/类
@Test
public void toXML() throws Exception {
    JAXBContext jc = JAXBContext.newInstance(MCRNavigationItem.class);
    Marshaller m = jc.createMarshaller();
    JDOMResult JDOMResult = new JDOMResult();
    m.marshal(this.item, JDOMResult);
    Element itemElement = JDOMResult.getDocument().getRootElement();

    XMLOutputter out = new XMLOutputter(Format.getPrettyFormat());
    out.output(itemElement, System.out);

    assertEquals("template_mysample", itemElement.getAttributeValue("template"));
    assertEquals("bold", itemElement.getAttributeValue("style"));
    assertEquals("_self", itemElement.getAttributeValue("target"));
    assertEquals("intern", itemElement.getAttributeValue("type"));
    assertEquals("true", itemElement.getAttributeValue("constrainPopUp"));
    assertEquals("false", itemElement.getAttributeValue("replaceMenu"));
    assertEquals("item.test.key", itemElement.getAttributeValue("i18nKey"));

    Element label1 = itemElement.getChildren().get(0);
    Element label2 = itemElement.getChildren().get(1);

    assertEquals("Deutschland", label1.getValue());
    assertEquals("England", label2.getValue());
}
 
开发者ID:MyCoRe-Org,项目名称:mycore,代码行数:26,代码来源:ItemTest.java

示例11: toXML

import org.jdom2.output.Format; //导入依赖的package包/类
@Test
public void toXML() throws Exception {
    JAXBContext jc = JAXBContext.newInstance(MCRNavigation.class);
    Marshaller m = jc.createMarshaller();
    JDOMResult JDOMResult = new JDOMResult();
    m.marshal(this.navigation, JDOMResult);
    Element navigationElement = JDOMResult.getDocument().getRootElement();

    XMLOutputter out = new XMLOutputter(Format.getPrettyFormat());
    out.output(navigationElement, System.out);

    // test attributes
    assertEquals("template_mysample", navigationElement.getAttributeValue("template"));
    assertEquals("/content", navigationElement.getAttributeValue("dir"));
    assertEquals("History Title", navigationElement.getAttributeValue("historyTitle"));
    assertEquals("/content/below/index.xml", navigationElement.getAttributeValue("hrefStartingPage"));
    assertEquals("Main Title", navigationElement.getAttributeValue("mainTitle"));
    // test children
    assertEquals(2, navigationElement.getChildren("menu").size());
    assertEquals(1, navigationElement.getChildren("insert").size());
}
 
开发者ID:MyCoRe-Org,项目名称:mycore,代码行数:22,代码来源:NavigationTest.java

示例12: toXML

import org.jdom2.output.Format; //导入依赖的package包/类
@Test
public final void toXML() throws IOException {
    MCRUserManager.updatePasswordHashToSHA256(this.user, this.user.getPassword());
    this.user.setEMail("[email protected]");
    this.user.setHint("JUnit Test");
    this.user.getSystemRoleIDs().add("admin");
    this.user.getSystemRoleIDs().add("editor");
    this.user.setLastLogin(new Date());
    this.user.setRealName("Test Case");
    this.user.getAttributes().put("tel", "555 4812");
    this.user.getAttributes().put("street", "Heidestraße 12");
    this.user.setOwner(this.user);
    MCRUserManager.updateUser(this.user);
    startNewTransaction();
    assertEquals("Too many users", 1, MCRUserManager.countUsers(null, null, null));
    assertEquals("Too many users", 1, MCRUserManager.listUsers(this.user).size());
    Document exportableXML = MCRUserTransformer.buildExportableXML(this.user);
    XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat());
    xout.output(exportableXML, System.out);
}
 
开发者ID:MyCoRe-Org,项目名称:mycore,代码行数:21,代码来源:MCRUserManagerTest.java

示例13: writeXML

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

示例14: getMCRObject

import org.jdom2.output.Format; //导入依赖的package包/类
/**
 * creates a MCRObject instance on base of JDOM document
 * @param doc
 *  MyCoRe object as XML.
 * @return
 * @throws JDOMException
 *  exception from underlying {@link MCREditorOutValidator}
 * @throws IOException
 *  exception from underlying {@link MCREditorOutValidator} or {@link XMLOutputter}
 * @throws SAXParseException
 * @throws MCRException
 */
static MCRObject getMCRObject(Document doc) throws JDOMException, IOException, MCRException, SAXParseException {
    String id = doc.getRootElement().getAttributeValue("ID");
    MCRObjectID objectID = MCRObjectID.getInstance(id);
    MCREditorOutValidator ev = new MCREditorOutValidator(doc, objectID);
    Document jdom_out = ev.generateValidMyCoReObject();
    if (ev.getErrorLog().size() > 0 && LOGGER.isDebugEnabled()) {
        XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat());
        StringWriter swOrig = new StringWriter();
        xout.output(doc, swOrig);
        LOGGER.debug("Input document \n{}", swOrig);
        for (String logMsg : ev.getErrorLog()) {
            LOGGER.debug(logMsg);
        }
        StringWriter swClean = new StringWriter();
        xout.output(jdom_out, swClean);
        LOGGER.debug("Results in \n{}", swClean);
    }
    return new MCRObject(jdom_out);
}
 
开发者ID:MyCoRe-Org,项目名称:mycore,代码行数:32,代码来源:MCRPersistenceHelper.java

示例15: generateValidMyCoReObject

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


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