org.apache.xml.serialize.OutputFormat Java Examples

The following examples show how to use org.apache.xml.serialize.OutputFormat. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AtsProjectConfiguration.java    From ats-framework with Apache License 2.0 6 votes vote down vote up
public void save() throws AtsConfigurationException {

        // save the XML file
        try {
            OutputFormat format = new OutputFormat(doc);
            format.setIndenting(true);
            format.setIndent(4);
            format.setLineWidth(1000);

            XMLSerializer serializer = new XMLSerializer(new FileOutputStream(new File(atsConfigurationFile)),
                                                         format);
            serializer.serialize(doc);
        } catch (Exception e) {
            throw new AtsConfigurationException("Error saving ATS configuration in '" + atsConfigurationFile
                                                + "'", e);
        }
    }
 
Example #2
Source File: JSONTemplateUtilities.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
public static String convertJsonToXML(JSONObject json) throws ParserConfigurationException, JSONException, IOException {
	String xml;
	DocumentBuilderFactory docBuildFactory = DocumentBuilderFactory.newInstance();
	DocumentBuilder docBuilder = docBuildFactory.newDocumentBuilder();
	Document dom = docBuilder.newDocument();

	Element xmlDom = extractXmlFromJson(json, dom, null);
	StringWriter outputStream = new StringWriter();
	OutputFormat outputFormat = new OutputFormat();
	outputFormat.setEncoding("UTF-8");
	outputFormat.setIndenting(true);
	XMLSerializer serializer = new XMLSerializer(outputStream, outputFormat);
	serializer.serialize(xmlDom);

	xml = outputStream.toString();
	return xml;
}
 
Example #3
Source File: XMLUtils.java    From jdal with Apache License 2.0 6 votes vote down vote up
/**
 * Serialize a Document to a String using JAXP with identation (4 spaces) 
 * @param doc to serialize
 * @return xml string
 */
public static String prettyDocumentToString(Document doc) {
	StringWriter writer = new StringWriter();
	OutputFormat out = new OutputFormat();
	out.setOmitXMLDeclaration(true);
	out.setIndenting(true);
	out.setIndent(4);
	out.setLineSeparator(System.getProperty("line.separator"));
	out.setLineWidth(Integer.MAX_VALUE);
	
	XMLSerializer serializer = new XMLSerializer(writer, out);
	try {
		Element rootElement = doc.getDocumentElement();
		serializer.serialize(rootElement);
	} catch (IOException e) { 
		log.error(e);
	}
	return writer.toString();
}
 
Example #4
Source File: XmlEditsVisitor.java    From hadoop with Apache License 2.0 6 votes vote down vote up
/**
 * Create a processor that writes to the file named and may or may not
 * also output to the screen, as specified.
 *
 * @param filename Name of file to write output to
 * @param printToScreen Mirror output to screen?
 */
public XmlEditsVisitor(OutputStream out)
    throws IOException {
  this.out = out;
  OutputFormat outFormat = new OutputFormat("XML", "UTF-8", true);
  outFormat.setIndenting(true);
  outFormat.setIndent(2);
  outFormat.setDoctype(null, null);
  XMLSerializer serializer = new XMLSerializer(out, outFormat);
  contentHandler = serializer.asContentHandler();
  try {
    contentHandler.startDocument();
    contentHandler.startElement("", "", "EDITS", new AttributesImpl());
  } catch (SAXException e) {
    throw new IOException("SAX error: " + e.getMessage());
  }
}
 
Example #5
Source File: XmlEditsVisitor.java    From big-c with Apache License 2.0 6 votes vote down vote up
/**
 * Create a processor that writes to the file named and may or may not
 * also output to the screen, as specified.
 *
 * @param filename Name of file to write output to
 * @param printToScreen Mirror output to screen?
 */
public XmlEditsVisitor(OutputStream out)
    throws IOException {
  this.out = out;
  OutputFormat outFormat = new OutputFormat("XML", "UTF-8", true);
  outFormat.setIndenting(true);
  outFormat.setIndent(2);
  outFormat.setDoctype(null, null);
  XMLSerializer serializer = new XMLSerializer(out, outFormat);
  contentHandler = serializer.asContentHandler();
  try {
    contentHandler.startDocument();
    contentHandler.startElement("", "", "EDITS", new AttributesImpl());
  } catch (SAXException e) {
    throw new IOException("SAX error: " + e.getMessage());
  }
}
 
Example #6
Source File: XmlSerializer.java    From cosmo with Apache License 2.0 6 votes vote down vote up
public static String serialize(XmlSerializable serializable)
    throws IOException {
    StringWriter out = new StringWriter();
    try {
        Document doc = BUILDER_FACTORY.newDocumentBuilder().newDocument();
        doc.appendChild(serializable.toXml(doc));
        
        OutputFormat format = new OutputFormat("xml", "UTF-8", true);
        XMLSerializer serializer =
            new XMLSerializer(out, format);
        serializer.setNamespaces(true);
        serializer.asDOMSerializer().serialize(doc);

        return out.toString();
    } catch (ParserConfigurationException e) {
        throw new CosmoParseException(e);
    }
}
 
Example #7
Source File: B2BParserHelper.java    From kfs with GNU Affero General Public License v3.0 6 votes vote down vote up
private byte[] addXMLNameSpace(Document xmlDoc,
                               String nameSpace){
    
    Node node = xmlDoc.getDocumentElement();
    Element element = (Element)node;
    
    element.setAttribute("xmlns", nameSpace);
    
    OutputFormat outputFormat = new OutputFormat(xmlDoc);
    outputFormat.setOmitDocumentType(true);
    
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    XMLSerializer serializer = new XMLSerializer( out,outputFormat );
    try {
        serializer.asDOMSerializer();
        serializer.serialize( xmlDoc.getDocumentElement());
    }
    catch (IOException e) {
        throw new RuntimeException(e);
    }
    
    return out.toByteArray();
}
 
Example #8
Source File: RepomdWriter.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
protected SimpleContentHandler getTemporaryHandler(OutputStream st) {
    OutputFormat of = new OutputFormat();
    of.setPreserveSpace(true);
    of.setOmitXMLDeclaration(true);
    XMLSerializer tmpSerial = new XMLSerializer(st, of);
    SimpleContentHandler tmpHandler = new SimpleContentHandler(tmpSerial);
    return tmpHandler;
}
 
Example #9
Source File: ProcessFile.java    From pdfxtk with Apache License 2.0 5 votes vote down vote up
public static void serializeXML
    (org.w3c.dom.Document resultDocument, Writer output)
    throws IOException
{
    // The third parameter in the constructor method for
    // _OutputFormat_ controls whether indenting should be
    // used.  Unfortunately, I have found some bugs in the
    // indenting implementation that have corrupted the text
    // so I have switched it off. 
     
    OutputFormat myOutputFormat =
        new OutputFormat(resultDocument,
                         "UTF-8",
                         true);

    // output used to be replaced with System.out
    XMLSerializer s = 
    new XMLSerializer(output, 
                          myOutputFormat);

    try {
    s.serialize(resultDocument);
    // next line added by THA 21.03.05
    output.flush();
    }
    catch (IOException e) {
        System.err.println("Couldn't serialize document: "+
           e.getMessage());
        throw e;
    }        

     // end of addition
}
 
Example #10
Source File: XMLUtils.java    From jdal with Apache License 2.0 5 votes vote down vote up
/** 
 * Element to String without format
 * 
 * @param elto to serialize
 * @return serialized elto
 */
public static String elementToString(Element elto) {
	StringWriter writer = new StringWriter();
	OutputFormat of = new OutputFormat();
	of.setOmitXMLDeclaration(true);
	XMLSerializer serializer = new XMLSerializer(writer, of);
	serializer.setNamespaces(true);
	try {
		serializer.serialize(elto);
	} catch (IOException ioe) {
		log.error(ioe);
	}
	return writer.toString();
}
 
Example #11
Source File: XMLUtils.java    From xcurator with Apache License 2.0 5 votes vote down vote up
public static byte[] asByteArray(Element element) throws IOException {
    ByteArrayOutputStream bis = new ByteArrayOutputStream();

    OutputFormat format = new OutputFormat(element.getOwnerDocument());
    XMLSerializer serializer = new XMLSerializer(
            bis, format);
    serializer.asDOMSerializer();
    serializer.serialize(element);

    return bis.toByteArray();
}
 
Example #12
Source File: ElementIdGenerator.java    From xcurator with Apache License 2.0 5 votes vote down vote up
public byte[] asByteArray(Element element) throws IOException {
    ByteArrayOutputStream bis = new ByteArrayOutputStream();

    OutputFormat format = new OutputFormat(element.getOwnerDocument());
    XMLSerializer serializer = new XMLSerializer(
            bis, format);
    serializer.asDOMSerializer();
    serializer.serialize(element);

    return bis.toByteArray();
}
 
Example #13
Source File: RepomdWriter.java    From spacewalk with GNU General Public License v2.0 5 votes vote down vote up
protected SimpleContentHandler getTemporaryHandler(OutputStream st) {
    OutputFormat of = new OutputFormat();
    of.setPreserveSpace(true);
    of.setOmitXMLDeclaration(true);
    XMLSerializer tmpSerial = new XMLSerializer(st, of);
    SimpleContentHandler tmpHandler = new SimpleContentHandler(tmpSerial);
    return tmpHandler;
}
 
Example #14
Source File: PackageManagerTest.java    From spacewalk with GNU General Public License v2.0 5 votes vote down vote up
protected SimpleContentHandler getTemporaryHandler(OutputStream st) {
    OutputFormat of = new OutputFormat();
    of.setPreserveSpace(true);
    of.setOmitXMLDeclaration(true);
    XMLSerializer tmpSerial = new XMLSerializer(st, of);
    return new SimpleContentHandler(tmpSerial);
}
 
Example #15
Source File: DocumentUtils.java    From cs-actions with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a String representation for the XML Document.
 *
 * @param xmlDocument the XML Document
 * @return String representation for the XML Document
 * @throws IOException
 */
public static String documentToString(Document xmlDocument) throws IOException {
    String encoding = (xmlDocument.getXmlEncoding() == null) ? "UTF-8" : xmlDocument.getXmlEncoding();
    OutputFormat format = new OutputFormat(xmlDocument);
    format.setLineWidth(65);
    format.setIndenting(true);
    format.setIndent(2);
    format.setEncoding(encoding);
    try (Writer out = new StringWriter()) {
        XMLSerializer serializer = new XMLSerializer(out, format);
        serializer.serialize(xmlDocument);
        return out.toString();
    }
}
 
Example #16
Source File: XPathReplacer.java    From maven-replacer-plugin with MIT License 5 votes vote down vote up
private String writeXml(Document doc) throws Exception {
	OutputFormat of = new OutputFormat(doc);
	of.setPreserveSpace(true);
	of.setEncoding(doc.getXmlEncoding());

	StringWriter sw = new StringWriter();
	XMLSerializer serializer = new XMLSerializer(sw, of);
	serializer.serialize(doc);
	return sw.toString();
}
 
Example #17
Source File: XMLReportTest.java    From testability-explorer with Apache License 2.0 5 votes vote down vote up
@Override
protected void setUp() throws Exception {
  handler.setOutputCharStream(out);
  handler.startDocument();
  OutputFormat format = new OutputFormat();
  format.setIndenting(true);
  handler.setOutputFormat(format);
}
 
Example #18
Source File: XMLHelpers.java    From SAMLRaider with MIT License 5 votes vote down vote up
public String getString(Document document, boolean indenting, int indent) throws IOException{
	OutputFormat format = new OutputFormat(document);
	format.setLineWidth(200);
	format.setIndenting(indenting);
	format.setIndent(indent);
	format.setPreserveEmptyAttributes(true);
	format.setEncoding("UTF-8");
	
	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	XMLSerializer serializer = new XMLSerializer(baos, format);
	serializer.asDOMSerializer();
	serializer.serialize(document);

	return baos.toString("UTF-8");
}
 
Example #19
Source File: PolicyEditorService.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Formats a given unformatted XML string
 *
 * @param xml
 * @return A CDATA wrapped, formatted XML String
 */
public String formatXML(String xml) {

    try {
        DocumentBuilder docBuilder;
        Document xmlDoc;

        // create the factory
        DocumentBuilderFactory docFactory = IdentityUtil.getSecuredDocumentBuilderFactory();
        docFactory.setIgnoringComments(true);

        // now use the factory to create the document builder
        docBuilder = docFactory.newDocumentBuilder();
        xmlDoc = docBuilder.parse(new ByteArrayInputStream(xml.getBytes(Charsets.UTF_8)));


        OutputFormat format = new OutputFormat(xmlDoc);
        format.setLineWidth(0);
        format.setIndenting(true);
        format.setIndent(2);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        XMLSerializer serializer = new XMLSerializer(baos, format);
        serializer.serialize(xmlDoc);

        xml = baos.toString("UTF-8");

    } catch (ParserConfigurationException pce) {
        throw new IllegalArgumentException("Failed to parse the unformatted XML String. ", pce);
    } catch (Exception e) {
        log.error("Error occured while formtting the unformatted XML String. ", e);
    }

    return "<![CDATA[" + xml + "]]>";
}
 
Example #20
Source File: PackageManagerTest.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
protected SimpleContentHandler getTemporaryHandler(OutputStream st) {
    OutputFormat of = new OutputFormat();
    of.setPreserveSpace(true);
    of.setOmitXMLDeclaration(true);
    XMLSerializer tmpSerial = new XMLSerializer(st, of);
    return new SimpleContentHandler(tmpSerial);
}
 
Example #21
Source File: WebServiceInterface.java    From quetzal with Eclipse Public License 2.0 4 votes vote down vote up
default void printDocument(Document doc) throws Exception {
	OutputFormat format = new OutputFormat(doc);
	format.setIndenting(true);
	XMLSerializer serializer = new XMLSerializer(System.out, format);
	serializer.serialize(doc);
}
 
Example #22
Source File: PolicyEditorService.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
/**
 * Formats a given unformatted XML string
 *
 * @param xml
 * @return A CDATA wrapped, formatted XML String
 */
public String formatXML(String xml) {

    try {
        // create the factory
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        docFactory.setIgnoringComments(true);
        docFactory.setNamespaceAware(true);
        docFactory.setExpandEntityReferences(false);
        SecurityManager securityManager = new SecurityManager();
        securityManager.setEntityExpansionLimit(ENTITY_EXPANSION_LIMIT);
        docFactory.setAttribute(SECURITY_MANAGER_PROPERTY, securityManager);
        DocumentBuilder docBuilder;
        Document xmlDoc;

        // now use the factory to create the document builder
        docFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        docFactory.setFeature(EXTERNAL_GENERAL_ENTITIES_URI, false);
        docBuilder = docFactory.newDocumentBuilder();
        docBuilder.setEntityResolver(new CarbonEntityResolver());
        xmlDoc = docBuilder.parse(new ByteArrayInputStream(xml.getBytes(Charsets.UTF_8)));


        OutputFormat format = new OutputFormat(xmlDoc);
        format.setLineWidth(0);
        format.setIndenting(true);
        format.setIndent(2);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        XMLSerializer serializer = new XMLSerializer(baos, format);
        serializer.serialize(xmlDoc);

        xml = baos.toString("UTF-8");

    } catch (ParserConfigurationException pce) {
        throw new IllegalArgumentException("Failed to parse the unformatted XML String. ", pce);
    } catch (Exception e) {
        log.error("Error occured while formtting the unformatted XML String. ", e);
    }

    return "<![CDATA[" + xml + "]]>";
}
 
Example #23
Source File: ReportGeneratorProvider.java    From testability-explorer with Apache License 2.0 4 votes vote down vote up
/**
 * Method to allow retaining a handle on preconfigured model objects.
 *
 * @param costModel Cost Model for the {@link ReportGenerator}
 * @param reportModel Can be {@code null} if {@link ReportFormat} is not
 *    {@link ReportFormat#html} or {@link ReportFormat#about}
 * @param sourceLoader Source Loader used by {@link ReportFormat#source} reports.
 * @return a ready to use {@link ReportGenerator}
 */
public ReportGenerator build(CostModel costModel, ReportModel reportModel,
    SourceLoader sourceLoader) {
  SourceLinker linker = new SourceLinker(
      options.getSrcFileLineUrl(), options.getSrcFileUrl());
  Configuration cfg = new Configuration();
  cfg.setTemplateLoader(new ClassPathTemplateLoader(PREFIX));
  BeansWrapper objectWrapper = new DefaultObjectWrapper();
  cfg.setObjectWrapper(objectWrapper);
  ResourceBundleModel bundleModel = new ResourceBundleModel(getBundle("messages"),
      objectWrapper);

  ReportGenerator report;
  switch (reportFormat) {
    case summary:
      report = new TextReportGenerator(out, costModel, options);
      break;
    case html:
      reportModel.setMessageBundle(bundleModel);
      reportModel.setSourceLinker(new SourceLinkerModel(linker));
      report = new FreemarkerReportGenerator(reportModel, out,
          FreemarkerReportGenerator.HTML_REPORT_TEMPLATE, cfg);
      break;
    case props:
      report = new PropertiesReportGenerator(out, costModel);
      break;
    case source:
      GradeCategories gradeCategories = new GradeCategories(options.getMaxExcellentCost(),
          options.getMaxAcceptableCost());
      report = new SourceReportGenerator(gradeCategories, sourceLoader,
          new File("te-report"), costModel, new Date(), options.getWorstOffenderCount(), cfg);
      break;
    case xml:
      XMLSerializer xmlSerializer = new XMLSerializer();
      xmlSerializer.setOutputByteStream(out);
      OutputFormat format = new OutputFormat();
      format.setIndenting(true);
      xmlSerializer.setOutputFormat(format);
      report = new XMLReportGenerator(xmlSerializer, costModel, options);
      break;
    case about:
      reportModel.setMessageBundle(bundleModel);
      reportModel.setSourceLinker(new SourceLinkerModel(linker));
      report = new FreemarkerReportGenerator(reportModel, out, "about/Report.html", cfg);
      break;
    default:
      throw new IllegalStateException("Unknown report format " + reportFormat);
  }
  return report;
}
 
Example #24
Source File: XMLUtil.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
public static String toXML(XMLObject xmlObject, boolean inlineEntity, boolean indent, XMLSerializer serializer) {
	Document document = xmlObject.toDocument(serializer);

	if (document == null)
		return "";

	OutputFormat format = new OutputFormat(document);

	/**
	 * PROBLEM WITH THE WRONG ENCODING SET TO THE XML STRING REPRESENTATION OF THE CHART TEMPLATE INSIDE THE xmlObject INPUT PARAMETER. FOR THIS
	 * APPLICATION, IT IS ALWAYS SET TO UTF-8, EVEN IF WE APPLY THE XML TEMPLATE WITH SOME DIFFERENT ENCODING (e.g. ISO-8859-1).
	 * 
	 * This line (encoding of the format) is commented due to the problem stated in the KNOWAGE-775 JIRA issue (title
	 * "COCKPIT-Chart: letters with accent are not correctly decoded").
	 * 
	 * It is found that the XML template of a chart has the UTF-8 encoding set in its header, no matter what is the encoding set on saving of the chart
	 * document (or uploading of the template with some different encoding, e.g. ISO-8859-1). It is not clear why this happens.
	 * 
	 * THE WORKAROUND: the encoding setting of the format will be skipped in order to avoid misbehavior and wrong encoding of the XML string representation
	 * (inside the xmlObject input parameter). This way we are keeping all the details provided in the template, such as specific Italian letters (such as
	 * à, è, ò etc.). Otherwise, this line would encode that XML string with the default encoding type (XML_HEADER_DEFAULT_ENCODING), that is ISO-8859-1. If
	 * we let this happen, we would lose mentioned specific letters and we will start getting weird ones on the chart (such as è).
	 * 
	 * @author Danilo Ristovski (danristo, [email protected])
	 */
	// format.setEncoding(XML_HEADER_DEFAULT_ENCODING);

	format.setIndenting(indent);
	format.setIndent(indent ? 2 : 0);
	format.setLineWidth(0);
	format.setLineSeparator(ConfigSingleton.LINE_SEPARATOR);
	format.setPreserveEmptyAttributes(true);
	StringWriter stringOut = new StringWriter();
	org.apache.xml.serialize.XMLSerializer serial = new org.apache.xml.serialize.XMLSerializer(stringOut, format);
	try {
		serial.asDOMSerializer();
		if (inlineEntity)
			serial.serialize(document);
		else
			serial.serialize(document.getDocumentElement());
	} // try
	catch (IOException ex) {
		TracerSingleton.log(Constants.NOME_MODULO, TracerSingleton.CRITICAL, "XMLUtil::toXML: ", ex);
	} // catch (IOException ex)
	return stringOut.toString();
}
 
Example #25
Source File: Xerces.java    From pdfxtk with Apache License 2.0 4 votes vote down vote up
public void writeDocument(Document document, Writer writer)
  throws IOException
{
  XMLSerializer s = new XMLSerializer(writer, new OutputFormat());
  s.serialize(document);
}
 
Example #26
Source File: UnescapingXmlSerializer.java    From spacewalk with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Constructor
 * @param writer the writer
 * @param format the output format
 */
public UnescapingXmlSerializer(Writer writer, OutputFormat format) {
    super(writer, format);
}
 
Example #27
Source File: UnescapingXmlSerializer.java    From uyuni with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Constructor
 * @param writer the writer
 * @param format the output format
 */
public UnescapingXmlSerializer(Writer writer, OutputFormat format) {
    super(writer, format);
}