Java Code Examples for javax.xml.parsers.DocumentBuilderFactory#setCoalescing()

The following examples show how to use javax.xml.parsers.DocumentBuilderFactory#setCoalescing() . These examples are extracted from open source projects. 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
/**
 * Assert that the specified XML file has not semantically changed,
 * although it might be identical to the original one due to format
 * changes, comments not being present, etc
 *
 * @param relativeFilePath relative path to file to be evaluated
 * @throws ParserConfigurationException
 * @throws IOException
 * @throws SAXException
 */
protected void assertEqualsXml(String relativeFilePath) throws ParserConfigurationException, IOException, SAXException {
    File originalFile = new File(appFolder, relativeFilePath);
    File transformedFile = new File(transformedAppFolder, relativeFilePath);

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    factory.setNamespaceAware(true);
    factory.setCoalescing(true);
    factory.setIgnoringElementContentWhitespace(true);
    factory.setIgnoringComments(true);

    DocumentBuilder builder = factory.newDocumentBuilder();
    Document originalXml = builder.parse(originalFile);
    Document transformedXml = builder.parse(transformedFile);

    originalXml.normalizeDocument();
    transformedXml.normalizeDocument();

    XMLUnit.setIgnoreAttributeOrder(true);
    XMLUnit.setIgnoreComments(true);
    XMLUnit.setIgnoreWhitespace(true);

    Assert.assertTrue(XMLUnit.compareXML(originalXml, transformedXml).similar());
}
 
Example 2
/**
 * Load an XML document from specified input stream, which must have the
 * requisite DTD URI.
 */
private static Document loadPrefsDoc(InputStream in) throws SAXException, IOException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setIgnoringElementContentWhitespace(true);
    dbf.setValidating(true);
    dbf.setCoalescing(true);
    dbf.setIgnoringComments(true);
    try {
        DocumentBuilder db = dbf.newDocumentBuilder();
        db.setEntityResolver(new Resolver());
        db.setErrorHandler(new EH());
        return db.parse(new InputSource(in));
    } catch (ParserConfigurationException e) {
        throw new AssertionError(e);
    }
}
 
Example 3
/**
 * Initializes the pool with a new set of configuration options.
 * 
 * @throws XMLParserException thrown if there is a problem initialzing the pool
 */
protected synchronized void initializePool() throws XMLParserException {
    if (!dirtyBuilderConfiguration) {
        // in case the pool was initialized by some other thread
        return;
    }

    DocumentBuilderFactory newFactory = DocumentBuilderFactory.newInstance();
    setAttributes(newFactory, builderAttributes);
    setFeatures(newFactory, builderFeatures);
    newFactory.setCoalescing(coalescing);
    newFactory.setExpandEntityReferences(expandEntityReferences);
    newFactory.setIgnoringComments(ignoreComments);
    newFactory.setIgnoringElementContentWhitespace(ignoreElementContentWhitespace);
    newFactory.setNamespaceAware(namespaceAware);
    newFactory.setSchema(schema);
    newFactory.setValidating(dtdValidating);
    newFactory.setXIncludeAware(xincludeAware);

    poolVersion++;
    dirtyBuilderConfiguration = false;
    builderFactory = newFactory;
    builderPool.clear();
}
 
Example 4
public Document parseXmlFile(String fileName) throws Exception {
    System.out.println("Parsing XML file... " + fileName);
    DocumentBuilder docBuilder = null;
    Document doc = null;
    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    docBuilderFactory.setCoalescing(true);
    docBuilderFactory.setXIncludeAware(true);
    System.out.println("Include: " + docBuilderFactory.isXIncludeAware());
    docBuilderFactory.setNamespaceAware(true);
    docBuilderFactory.setExpandEntityReferences(true);

    docBuilder = docBuilderFactory.newDocumentBuilder();

    File sourceFile = new File(fileName);
    doc = docBuilder.parse(sourceFile);

    System.out.println("XML file parsed");
    return doc;

}
 
Example 5
@Test
  public void testXmlTemplate() throws IOException, JsonDataGeneratorException, SAXException, ParserConfigurationException, XpathException {
      parser.generateTestDataJson(this.getClass().getClassLoader().getResource("xmlfunctionWithRepeat.xml"), outputStream);
      
      ByteArrayInputStream inputstream = new ByteArrayInputStream(outputStream.toByteArray());
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      dbf.setNamespaceAware(true);
      dbf.setCoalescing(true);
      dbf.setIgnoringElementContentWhitespace(true);
      dbf.setIgnoringComments(true);
      DocumentBuilder db = dbf.newDocumentBuilder();

      Document doc = db.parse(inputstream);
      XpathEngine simpleXpathEngine = XMLUnit.newXpathEngine();
      String value = simpleXpathEngine.evaluate("//root/tags", doc);
assertEquals(value.split(",").length, 7);
assertTrue(simpleXpathEngine.evaluate("//root/element[1]/name", doc).length() > 1);
assertTrue(simpleXpathEngine.evaluate("//root/element[2]/name", doc).length() > 1);
assertTrue(simpleXpathEngine.evaluate("//root/friends/friend[1]/name", doc).length() > 1);
assertTrue(simpleXpathEngine.evaluate("//root/friends/friend[2]/name", doc).length() > 1);
assertTrue(simpleXpathEngine.evaluate("//root/friends/friend[3]/name", doc).length() > 1);
  }
 
Example 6
/**
 * Compare contents of golden file with test output file by their document
 * representation.
 * Here we ignore the white space and comments. return true if they're
 * lexical identical.
 * @param goldfile Golden output file name.
 * @param resultFile Test output file name.
 * @return true if two file's document representation are identical.
 *         false if two file's document representation are not identical.
 * @throws javax.xml.parsers.ParserConfigurationException if the
 *         implementation is not available or cannot be instantiated.
 * @throws SAXException If any parse errors occur.
 * @throws IOException if an I/O error occurs reading from the file or a
 *         malformed or unmappable byte sequence is read .
 */
public static boolean compareDocumentWithGold(String goldfile, String resultFile)
        throws ParserConfigurationException, SAXException, IOException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    factory.setCoalescing(true);
    factory.setIgnoringElementContentWhitespace(true);
    factory.setIgnoringComments(true);
    DocumentBuilder db = factory.newDocumentBuilder();

    Document goldD = db.parse(Paths.get(goldfile).toFile());
    goldD.normalizeDocument();
    Document resultD = db.parse(Paths.get(resultFile).toFile());
    resultD.normalizeDocument();
    return goldD.isEqualNode(resultD);
}
 
Example 7
Source Project: jeddict   File: DOMHelper.java    License: Apache License 2.0 6 votes vote down vote up
private DocumentBuilder getDocumentBuilder() {
    DocumentBuilder builder = null;

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(false);
    factory.setIgnoringComments(false);
    factory.setIgnoringElementContentWhitespace(false);
    factory.setCoalescing(false);
    factory.setExpandEntityReferences(false);
    factory.setValidating(false);

    try {
        builder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException ex) {
        Exceptions.printStackTrace(ex);
    }

    return builder;
}
 
Example 8
private static Document loadPrefsDoc(InputStream in)
    throws SAXException, IOException
{
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setIgnoringElementContentWhitespace(true);
    dbf.setValidating(true);
    dbf.setCoalescing(true);
    dbf.setIgnoringComments(true);
    try {
        DocumentBuilder db = dbf.newDocumentBuilder();
        db.setEntityResolver(new Resolver());
        db.setErrorHandler(new EH());
        return db.parse(new InputSource(in));
    } catch (ParserConfigurationException e) {
        throw new AssertionError(e);
    }
}
 
Example 9
Source Project: cxf   File: JsSimpleDomParser.java    License: Apache License 2.0 5 votes vote down vote up
public JsSimpleDomParser() {
    try {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(true);
        documentBuilderFactory.setCoalescing(true);
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        throw new RuntimeException(e);
    }
}
 
Example 10
Source Project: ph-commons   File: XMLFactory.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create a new {@link DocumentBuilderFactory} using the defaults defined in
 * this class ({@link #DEFAULT_DOM_NAMESPACE_AWARE},
 * {@link #DEFAULT_DOM_VALIDATING} etc.).
 *
 * @return Never <code>null</code>.
 */
@Nonnull
public static DocumentBuilderFactory createDefaultDocumentBuilderFactory ()
{
  final DocumentBuilderFactory aDocumentBuilderFactory = DocumentBuilderFactory.newInstance ();
  aDocumentBuilderFactory.setNamespaceAware (DEFAULT_DOM_NAMESPACE_AWARE);
  aDocumentBuilderFactory.setValidating (DEFAULT_DOM_VALIDATING);
  aDocumentBuilderFactory.setIgnoringElementContentWhitespace (DEFAULT_DOM_IGNORING_ELEMENT_CONTENT_WHITESPACE);
  aDocumentBuilderFactory.setExpandEntityReferences (DEFAULT_DOM_EXPAND_ENTITY_REFERENCES);
  aDocumentBuilderFactory.setIgnoringComments (DEFAULT_DOM_IGNORING_COMMENTS);
  aDocumentBuilderFactory.setCoalescing (DEFAULT_DOM_COALESCING);
  try
  {
    // Set secure processing to be the default. This is anyway the default in
    // JDK8
    aDocumentBuilderFactory.setFeature (EXMLParserFeature.SECURE_PROCESSING.getName (), true);
  }
  catch (final ParserConfigurationException ex1)
  {
    // Ignore
  }
  try
  {
    aDocumentBuilderFactory.setXIncludeAware (DEFAULT_DOM_XINCLUDE_AWARE);
  }
  catch (final UnsupportedOperationException ex)
  {
    // Ignore
  }
  return aDocumentBuilderFactory;
}
 
Example 11
/**
 * Test the default functionality of newInstance method. To test
 * the isCoalescing method and setCoalescing This checks to see if the CDATA
 * and text nodes got combined In that case it will print "&lt;xml&gt;This
 * is not parsed&lt;/xml&gt; yet".
 * @throws Exception If any errors occur.
 */
@Test
public void testCheckDocumentBuilderFactory02() throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setCoalescing(true);
    DocumentBuilder docBuilder = dbf.newDocumentBuilder();
    Document doc = docBuilder.parse(new File(XML_DIR, "DocumentBuilderFactory01.xml"));
    Element e = (Element) doc.getElementsByTagName("html").item(0);
    NodeList nl = e.getChildNodes();
    assertEquals(nl.getLength(), 1);
}
 
Example 12
protected static DocumentBuilder getDocumentBuilder(boolean coalesce) {
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setCoalescing(coalesce);
        return dbf.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        String message = "Error constructing document builder";
        LOG.error(message, e);
        throw new WorkflowRuntimeException(message, e);
    }
}
 
Example 13
/**
 * Parses the string as the body of an XML document and returns the document element.
 * @param source source string.
 * @return document element.
 * @throws Exception if parser can not be constructed or source is not a valid XML document.
 */
private Document parse(final String source) throws Exception {
  DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  factory.setNamespaceAware(false);
  factory.setCoalescing(true);

  DocumentBuilder builder = factory.newDocumentBuilder();
  Reader reader = new StringReader(source);

  return builder.parse(new InputSource(reader));
}
 
Example 14
/**
 * Parses the string as the body of an XML document and returns the document element.
 * @param source source string.
 * @return document element.
 * @throws Exception if parser can not be constructed or source is not a valid XML document.
 */
private Element parse(final String source) throws Exception {
  DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  factory.setNamespaceAware(false);
  factory.setCoalescing(true);

  DocumentBuilder builder = factory.newDocumentBuilder();
  Reader reader = new StringReader(source);
  Document doc = builder.parse(new InputSource(reader));

  return doc.getDocumentElement();
}
 
Example 15
Source Project: j2objc   File: Support_Xml.java    License: Apache License 2.0 5 votes vote down vote up
public static Document domOf(String xml) throws Exception {
    // DocumentBuilderTest assumes we're using DocumentBuilder to do this parsing!
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setCoalescing(true);
    dbf.setExpandEntityReferences(true);

    ByteArrayInputStream stream = new ByteArrayInputStream(xml.getBytes());
    DocumentBuilder builder = dbf.newDocumentBuilder();

    return builder.parse(stream);
}
 
Example 16
Source Project: ph-commons   File: MicroHelperTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testConvertToMicroNode () throws SAXException, IOException, ParserConfigurationException
{
  final String sXML = "<?xml version='1.0'?>" +
                      "<!DOCTYPE root [ <!ENTITY sc \"sc.exe\"> <!ELEMENT root (child, child2)> <!ELEMENT child (#PCDATA)> <!ELEMENT child2 (#PCDATA)> ]>" +
                      "<root attr='value'>" +
                      "<![CDATA[hihi]]>" +
                      "text" +
                      "&sc;" +
                      "<child xmlns='http://myns' a='b' />" +
                      "<child2 />" +
                      "<!-- comment -->" +
                      "<?stylesheet x y z?>" +
                      "</root>";
  final DocumentBuilderFactory aDBF = XMLFactory.createDefaultDocumentBuilderFactory ();
  aDBF.setCoalescing (false);
  aDBF.setIgnoringComments (false);
  final Document doc = aDBF.newDocumentBuilder ().parse (new StringInputStream (sXML, StandardCharsets.ISO_8859_1));
  assertNotNull (doc);
  final IMicroNode aNode = MicroHelper.convertToMicroNode (doc);
  assertNotNull (aNode);
  try
  {
    MicroHelper.convertToMicroNode (null);
    fail ();
  }
  catch (final NullPointerException ex)
  {}
}
 
Example 17
private DocumentBuilderFactory createDocumentBuilderFactory() {
	DocumentBuilderFactory result = DocumentBuilderFactory.newInstance();
	result.setNamespaceAware(namespaceAware);
	result.setCoalescing(coalescing);
	return result;
}
 
Example 18
Source Project: rice   File: EmailNode.java    License: Educational Community License v2.0 4 votes vote down vote up
protected DocumentBuilder getDocumentBuilder(boolean coalesce) throws Exception {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setCoalescing(coalesce);
return dbf.newDocumentBuilder();
   }
 
Example 19
protected DocumentBuilder getDocumentBuilder(boolean coalesce) throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setCoalescing(coalesce);
    return dbf.newDocumentBuilder();
}
 
Example 20
@Override
protected void setUp() throws Exception {
    super.setUp();

    /* build the dictionaries */
    mds_catsup = buildDictionaryCollection(
        "registers/catsup/Elements.xml",
        "registers/catsup/Groups.xml",
        "registers/catsup/Types.xml"
    );

    assertNotNull(mds_catsup);

    /* build the dictionaries */
    mds_brown_sauce = buildDictionaryCollection(
        "registers/brown_sauce/Elements.xml",
        "registers/brown_sauce/Groups.xml",
        "registers/brown_sauce/Types.xml"
    );

    assertNotNull(mds_brown_sauce);

    /* build the dictionaries */
    mds_snapshot = buildDictionaryCollection(
        "registers/snapshot/Elements.xml",
        "registers/snapshot/Groups.xml",
        "registers/snapshot/Types.xml"
    );

    assertNotNull(mds_snapshot);

    mds_ponzu = buildDictionaryCollection(
        "registers/ponzu/Elements.xml",
        "registers/ponzu/Groups.xml",
        "registers/ponzu/Types.xml"
    );

    assertNotNull(mds_ponzu);


    /* setup the doc builder */
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setCoalescing(true);
    dbf.setIgnoringElementContentWhitespace(true);
    dbf.setIgnoringComments(true);
    db = dbf.newDocumentBuilder();

    assertNotNull(db);
}