本文整理匯總了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 );
}
示例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");
}
}
示例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;
}
示例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);
}
}
示例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);
}
}
示例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());
}
示例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;
}
示例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());
}
示例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);
});
}
示例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());
}
示例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());
}
示例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);
}
示例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();
}
示例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);
}
示例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;
}