Java Code Examples for javax.xml.parsers.DocumentBuilderFactory.setIgnoringComments()

The following are Jave code examples for showing how to use setIgnoringComments() of the javax.xml.parsers.DocumentBuilderFactory class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: openjdk-jdk10   File: Bug6564400.java   View Source Code Vote up 7 votes
@Test
public void testDOM() throws ParserConfigurationException, SAXException, IOException {
    InputStream xmlFile = getClass().getResourceAsStream("Bug6564400.xml");

    // Set the options on the DocumentFactory to remove comments, remove
    // whitespace
    // and validate against the schema.
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    docFactory.setIgnoringComments(true);
    docFactory.setIgnoringElementContentWhitespace(true);
    docFactory.setSchema(schema);

    DocumentBuilder parser = docFactory.newDocumentBuilder();
    Document xmlDoc = parser.parse(xmlFile);

    boolean ok = dump(xmlDoc, true);
    Assert.assertEquals(true, ok);
}
 
Example 2
Project: butterfly   File: CompareXMLFiles.java   View Source Code Vote up 6 votes
@Override
protected boolean compare(File baselineFile, File comparisonFile) {
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

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

        DocumentBuilder builder = factory.newDocumentBuilder();
        Document baselineXml = builder.parse(baselineFile);
        Document comparisonXml = builder.parse(comparisonFile);

        baselineXml.normalizeDocument();
        comparisonXml.normalizeDocument();

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

        return XMLUnit.compareXML(baselineXml, comparisonXml).similar();
    } catch (SAXException | IOException | ParserConfigurationException e) {
        throw new TransformationUtilityException("An exception happened when comparing the two XML files", e);
    }
}
 
Example 3
Project: openjdk-jdk10   File: JAXPTestUtilities.java   View Source Code Vote up 6 votes
/**
 * 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 4
Project: tomcat7   File: DomUtil.java   View Source Code Vote up 6 votes
/** Read XML as DOM.
 */
public static Document readXml(InputStream is)
    throws SAXException, IOException, ParserConfigurationException
{
    DocumentBuilderFactory dbf =
        DocumentBuilderFactory.newInstance();

    dbf.setValidating(false);
    dbf.setIgnoringComments(false);
    dbf.setIgnoringElementContentWhitespace(true);
    //dbf.setCoalescing(true);
    //dbf.setExpandEntityReferences(true);

    DocumentBuilder db = null;
    db = dbf.newDocumentBuilder();
    db.setEntityResolver( new NullResolver() );

    // db.setErrorHandler( new MyErrorHandler());

    Document doc = db.parse(is);
    return doc;
}
 
Example 5
Project: FlexibleRichTextView   File: GlueSettingsParser.java   View Source Code Vote up 6 votes
public GlueSettingsParser() throws ResourceParseException {
	try {
		setTypeMappings();
		setStyleMappings();
		DocumentBuilderFactory factory = DocumentBuilderFactory
				.newInstance();
		factory.setIgnoringElementContentWhitespace(true);
		factory.setIgnoringComments(true);
		root = factory.newDocumentBuilder()
				.parse(AjLatexMath.getAssetManager().open(RESOURCE_NAME))
				.getDocumentElement();
		parseGlueTypes();
	} catch (Exception e) { // JDOMException or IOException
		throw new XMLResourceParseException(RESOURCE_NAME, e);
	}
}
 
Example 6
Project: openjdk-jdk10   File: Bug6879614Test.java   View Source Code Vote up 6 votes
@Test
public void testAttributeCaching() {
    File xmlFile = new File(getClass().getResource("Bug6879614.xml").getFile());
    DocumentBuilderFactory _documentBuilderFactory = DocumentBuilderFactory.newInstance();
    _documentBuilderFactory.setValidating(false);
    _documentBuilderFactory.setIgnoringComments(true);
    _documentBuilderFactory.setIgnoringElementContentWhitespace(true);
    _documentBuilderFactory.setCoalescing(true);
    _documentBuilderFactory.setExpandEntityReferences(true);
    _documentBuilderFactory.setNamespaceAware(true);
    DocumentBuilder _documentBuilder = null;
    try {
        _documentBuilder = _documentBuilderFactory.newDocumentBuilder();
    } catch (ParserConfigurationException pce) {
        pce.printStackTrace();
    }

    Document xmlDoc = null;
    try {
        xmlDoc = _documentBuilder.parse(xmlFile);
        if (xmlDoc == null) {
            System.out.println("Hello!!!, there is a problem here");
        } else {
            System.out.println("Good, the parsing went through fine.");
        }
    } catch (SAXException se) {
        se.printStackTrace();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
}
 
Example 7
Project: ibench   File: AbstractCheckExpectedOutputTester.java   View Source Code Vote up 6 votes
public void compareFile(String fileLeft, String fileRight) throws SAXException, IOException, ParserConfigurationException, TransformerException {
	DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
	dbf.setNamespaceAware(true);
	dbf.setCoalescing(true);
	dbf.setIgnoringElementContentWhitespace(true);
	dbf.setIgnoringComments(true);

	DocumentBuilder db = dbf.newDocumentBuilder();

	Document doc1 = db.parse(new File(expectedPath + "/" + fileRight + ".xml"));
	doc1.normalizeDocument();

	Document doc2 = db.parse(new File(OUT_DIR + "/" + fileLeft + ".xml"));
	doc2.normalizeDocument();

	assertEquals("Output <" + fileLeft + "> is not the same as expected output <" +
			fileRight + ">", 
			docToString(doc1), 
			docToString(doc2));
}
 
Example 8
Project: lams   File: BasicParserPool.java   View Source Code Vote up 6 votes
/**
 * 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 9
Project: ats-framework   File: ConfigurationParser.java   View Source Code Vote up 5 votes
/**
 * Initializer method of the parser. Initializes the document instance.
 * @param inputStream - configuration file input stream to be parsed
 * @param systemId Provide a base for resolving relative URIs.
 * @throws IOException - if the streamed object is not found
 */
private void inititalizeParser( InputStream inputStream, String systemId ) throws IOException,
                                                                           SAXException,
                                                                           ParserConfigurationException {

    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setIgnoringElementContentWhitespace(true);
    documentBuilderFactory.setNamespaceAware(true);
    documentBuilderFactory.setValidating(false);
    documentBuilderFactory.setIgnoringComments(true);

    try {
        // skip DTD validation
        documentBuilderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar",
                                          false);
        documentBuilderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd",
                                          false);

        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        mDocument = documentBuilder.parse(inputStream, systemId);

        /* NOTE:
         * XSD Validation process is performed after the XML parsing (not during), 
         * because when we do it during the parsing, the XML Document element adds attributes which has a default values in the XSD.
         * In our case for example, it adds lock="true" for all 'table' elements and when the database is oracle
         * we log WARN messages. It's wrong. That's why we do the validation after parsing the XML.
         */

        ConfigurationParser.class.getClassLoader().getResource("agent_descriptor.xsd");

        // XSD Validation
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = schemaFactory.newSchema(this.getClass()
                                                    .getClassLoader()
                                                    .getResource("agent_descriptor.xsd"));
        Validator validator = schema.newValidator();
        validator.validate(new DOMSource(mDocument));

    } catch (ParserConfigurationException pce) {
        log.error(pce.getMessage());
        throw pce;
    } catch (IOException ioe) {
        log.error(ioe.getMessage());
        throw ioe;
    } catch (SAXException saxe) {
        log.error(saxe.getMessage());
        throw saxe;
    }
}
 
Example 10
Project: L2J-Global   File: MerchantPriceConfigTable.java   View Source Code Vote up 5 votes
public void loadXML() throws SAXException, IOException, ParserConfigurationException
{
	final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	factory.setValidating(false);
	factory.setIgnoringComments(true);
	final File file = new File(Config.DATAPACK_ROOT + "/data/" + MPCS_FILE);
	if (file.exists())
	{
		int defaultPriceConfigId;
		final Document doc = factory.newDocumentBuilder().parse(file);
		
		Node n = doc.getDocumentElement();
		final Node dpcNode = n.getAttributes().getNamedItem("defaultPriceConfig");
		if (dpcNode == null)
		{
			throw new IllegalStateException("merchantPriceConfig must define an 'defaultPriceConfig'");
		}
		defaultPriceConfigId = Integer.parseInt(dpcNode.getNodeValue());
		
		MerchantPriceConfig mpc;
		for (n = n.getFirstChild(); n != null; n = n.getNextSibling())
		{
			mpc = parseMerchantPriceConfig(n);
			if (mpc != null)
			{
				_mpcs.put(mpc.getId(), mpc);
			}
		}
		
		final MerchantPriceConfig defaultMpc = this.getMerchantPriceConfig(defaultPriceConfigId);
		if (defaultMpc == null)
		{
			throw new IllegalStateException("'defaultPriceConfig' points to an non-loaded priceConfig");
		}
		_defaultMpc = defaultMpc;
	}
}
 
Example 11
Project: FlexibleRichTextView   File: TeXFormulaSettingsParser.java   View Source Code Vote up 5 votes
public TeXFormulaSettingsParser(InputStream file, String name)
		throws ResourceParseException, IOException {
	try {
		DocumentBuilderFactory factory = DocumentBuilderFactory
				.newInstance();
		factory.setIgnoringElementContentWhitespace(true);
		factory.setIgnoringComments(true);
		root = factory.newDocumentBuilder().parse(file)
				.getDocumentElement();
	} catch (Exception e) { // JDOMException or IOException
		throw new XMLResourceParseException(name, e);
	}
	file.close();
}
 
Example 12
Project: joai-project   File: XMLDocReader.java   View Source Code Vote up 5 votes
/**
 *  Gets a org.w3c.dom.Document for this record. This method is optimized to create only one DOM when
 *  accessed multiple times for the same XMLDocReader.
 *
 * @return    A org.w3c.dom.Document, or null if unable to read.
 */
public org.w3c.dom.Document getW3CXmlDoc() {
	if (w3cXmlDoc != null)
		return w3cXmlDoc;

	DocumentBuilderFactory docfactory
		 = DocumentBuilderFactory.newInstance();
	docfactory.setCoalescing(true);
	docfactory.setExpandEntityReferences(true);
	docfactory.setIgnoringComments(true);

	docfactory.setNamespaceAware(true);

	// We must set validation false since jdk1.4 parser
	// doesn't know about schemas.
	docfactory.setValidating(false);

	// Ignore whitespace doesn't work unless setValidating(true),
	// according to javadocs.
	docfactory.setIgnoringElementContentWhitespace(false);
	try {
		DocumentBuilder docbuilder = docfactory.newDocumentBuilder();
		w3cXmlDoc = docbuilder.parse(getXml());
	} catch (Throwable e) {
		return null;
	}
	return w3cXmlDoc;
}
 
Example 13
Project: ciguan   File: AsXmlTool.java   View Source Code Vote up 5 votes
/**
 * Load XML resource.
 *
 * @param pResource the resource
 * @return the document
 * @throws Exception in case a problem occurred
 */
public static Document loadXmlResource(String pResource) throws Exception {

    String tResource = (pResource.startsWith("/") ? pResource.substring(1) : pResource);
    InputStream tStream = null;

    /**
     * Try own class loader first, then the system class loader
     */
    tStream = AsXmlTool.class.getClassLoader().getResourceAsStream(tResource);
    if (tStream == null) {
        tStream = ClassLoader.getSystemResourceAsStream(tResource);
    }
    if (tStream == null) {
        tStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(tResource);
    }        
    if (tStream == null) {
        throw new RuntimeException("Failed to locate module '" + pResource + "'");
    }
    
    DocumentBuilderFactory tFactory = DocumentBuilderFactory.newInstance();
    tFactory.setIgnoringComments(true);
    tFactory.setNamespaceAware(false); // No namespaces: this is default
    tFactory.setValidating(false); // Don't validate DTD: also default
    
    DocumentBuilder tParser = tFactory.newDocumentBuilder();
    
    return tParser.parse(tStream);
}
 
Example 14
Project: geomapapp   File: XML_Menu.java   View Source Code Vote up 5 votes
public static boolean validate(File mainMenuFile) {
	try {
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		dbf.setIgnoringComments(true);
		DocumentBuilder db = dbf.newDocumentBuilder();
		Document dom = db.parse(mainMenuFile);
	} catch (SAXException e) {
		return false;
	} catch (ParserConfigurationException pe) {
		return false;
	} catch (IOException io) {
		return false;
	}
	return true;
}
 
Example 15
Project: hadoop   File: TestQueuePlacementPolicy.java   View Source Code Vote up 5 votes
private QueuePlacementPolicy parse(String str) throws Exception {
  // Read and parse the allocations file.
  DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
      .newInstance();
  docBuilderFactory.setIgnoringComments(true);
  DocumentBuilder builder = docBuilderFactory.newDocumentBuilder();
  Document doc = builder.parse(IOUtils.toInputStream(str));
  Element root = doc.getDocumentElement();
  return QueuePlacementPolicy.fromXml(root, configuredQueues, conf);
}
 
Example 16
Project: lams   File: StaticBasicParserPool.java   View Source Code Vote up 5 votes
/**
 * Initializes the pool with a new set of configuration options.
 * 
 * @throws XMLParserException thrown if there is a problem initialzing the pool
 */
protected synchronized void initializeFactory() throws XMLParserException {
    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);
    builderFactory = newFactory;
}
 
Example 17
Project: openjdk-jdk10   File: DocumentBuilderFactoryTest.java   View Source Code Vote up 5 votes
/**
 * Test the setIgnoringComments. By default it is set to false.
 * explicitly setting it to false, it recognizes the comment which is in
 * Element Node Hence the Element's child node is not null.
 * @throws Exception If any errors occur.
 */
@Test
public void testCheckDocumentBuilderFactory09() throws Exception {
    try (FileInputStream fis = new FileInputStream(new File(
            XML_DIR, "DocumentBuilderFactory07.xml"))) {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setIgnoringComments(false);
        DocumentBuilder docBuilder = dbf.newDocumentBuilder();
        Document doc = docBuilder.parse(fis);
        Element e = (Element) doc.getElementsByTagName("body").item(0);
        NodeList nl = e.getChildNodes();
        assertNotNull(nl.item(0).getNodeValue());
    }
}
 
Example 18
Project: LibraSock   File: XmlUtils.java   View Source Code Vote up 5 votes
public static Document load(String paramString) throws Exception {
	DocumentBuilderFactory localDocumentBuilderFactory = DocumentBuilderFactory.newInstance();
	localDocumentBuilderFactory.setIgnoringComments(false);
	localDocumentBuilderFactory.setIgnoringElementContentWhitespace(false);
	localDocumentBuilderFactory.setValidating(false);
	localDocumentBuilderFactory.setCoalescing(true);
	DocumentBuilder localDocumentBuilder = localDocumentBuilderFactory.newDocumentBuilder();
	return localDocumentBuilder.parse(paramString);
}
 
Example 19
Project: LibraSock   File: XmlUtils.java   View Source Code Vote up 5 votes
public static Document load(File paramFile) throws Exception {
	DocumentBuilderFactory localDocumentBuilderFactory = DocumentBuilderFactory.newInstance();
	localDocumentBuilderFactory.setIgnoringComments(false);
	localDocumentBuilderFactory.setIgnoringElementContentWhitespace(false);
	localDocumentBuilderFactory.setValidating(false);
	localDocumentBuilderFactory.setCoalescing(true);
	DocumentBuilder localDocumentBuilder = localDocumentBuilderFactory.newDocumentBuilder();
	return localDocumentBuilder.parse(paramFile);
}
 
Example 20
Project: LibraSock   File: XmlUtils.java   View Source Code Vote up 5 votes
public static Document loadString(String paramString) throws Exception {
	DocumentBuilderFactory localDocumentBuilderFactory = DocumentBuilderFactory.newInstance();
	localDocumentBuilderFactory.setIgnoringComments(false);
	localDocumentBuilderFactory.setIgnoringElementContentWhitespace(false);
	localDocumentBuilderFactory.setValidating(false);
	localDocumentBuilderFactory.setCoalescing(false);
	DocumentBuilder localDocumentBuilder = localDocumentBuilderFactory.newDocumentBuilder();
	char[] arrayOfChar = new char[paramString.length()];
	paramString.getChars(0, paramString.length(), arrayOfChar, 0);
	InputSource localInputSource = new InputSource(new CharArrayReader(arrayOfChar));
	return localDocumentBuilder.parse(localInputSource);
}