Exemplo n.º 1
0
  /**
   * Prevede DOM na String s danym kodovanim.
   *
   * @param node
   * @param encoding muze byt null
   * @param pretty prida nove radky za elementy
   * @return
   * @throws ProblemException
   */
  public static String domToString(Node node, String encoding, boolean pretty)
      throws ProblemException {

    if (node == null) return null;

    String usedEncoding = encoding == null ? DEFAULT_ENCODING : encoding;

    if (Checker.isBlank(usedEncoding)) {
      throw new ProblemException(XmlProblem.INVALID_ENCODING);
    }

    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    DOMSource source = new DOMSource(node);

    try (StringWriter writer = new StringWriter()) {
      StreamResult result = new StreamResult(writer);

      Transformer transformer = transformerFactory.newTransformer();
      transformer.setOutputProperty(OutputKeys.METHOD, "xml");
      transformer.setOutputProperty(OutputKeys.ENCODING, usedEncoding);
      transformer.setOutputProperty(OutputKeys.INDENT, pretty ? "yes" : "no");
      transformer.setOutputProperty(OutputKeys.STANDALONE, "no");
      transformer.transform(source, result);

      return writer.toString();

    } catch (Exception e) {
      logger.error(e.toString(), e);
      throw new ProblemException(e, XmlProblem.SERIALIZE_DOM);
    }
  }
Exemplo n.º 2
0
  /**
   * Prevede XML retezec na DOM dokument.
   *
   * @param xml retezec obsahujici XML nebo HTML
   * @return DOM dokument
   * @throws ProblemException pokud dojde k chybe pri prevodu
   */
  public static Document createDOMDocument(String xml) throws ProblemException {

    if (Checker.isBlank(xml)) return null;

    try {
      InputSource is = new InputSource(new StringReader(xml));
      return getDocBuilder().parse(is);

    } catch (IOException | SAXException e) {
      logger.error(e.toString(), e);
      throw new ProblemException(e, XmlProblem.PARSING, e.toString());
    }
  }