javax.xml.parsers.DocumentBuilder#setErrorHandler ( )源码实例Demo

下面列出了javax.xml.parsers.DocumentBuilder#setErrorHandler ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: packagedrone   文件: ExtractorImpl.java
@Override
public void extractMetaData ( final Extractor.Context context, final Map<String, String> metadata ) throws Exception
{
    final DocumentBuilder db = this.xml.newDocumentBuilder ();

    try ( InputStream in = new BufferedInputStream ( Files.newInputStream ( context.getPath () ) ) )
    {
        db.setErrorHandler ( null );
        // use a stream, to prevent possible redirects to the file system
        final Document doc = db.parse ( in );
        if ( "artifacts".equals ( doc.getDocumentElement ().getTagName () ) )
        {
            processArtifacts ( context, metadata, doc );
        }
        else if ( "units".equals ( doc.getDocumentElement ().getTagName () ) )
        {
            processMetadata ( context, metadata, doc );
        }
    }
    catch ( final Exception e )
    {
        // ignore
    }
}
 
源代码2 项目: sarl   文件: StandardSREInstallTest.java
@Test
public void setFromXML() throws Exception {
	String[] expected = new String[] { "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>",
			"<SRE name=\"Hello\" mainClass=\"io.sarl.Boot\" libraryPath=\"" + this.path.toPortableString()
					+ "\" standalone=\"true\">",
			"<libraryLocation packageRootPath=\"\" sourcePath=\"\" systemLibraryPath=\"" + this.path.toPortableString()
					+ "\"/>",
			"<libraryLocation packageRootPath=\"\" sourcePath=\"\" systemLibraryPath=\"x.jar\"/>",
			"<libraryLocation packageRootPath=\"\" sourcePath=\"\" systemLibraryPath=\"y.jar\"/>",
			"<libraryLocation packageRootPath=\"\" sourcePath=\"\" systemLibraryPath=\"z.jar\"/>", "</SRE>", };
	StringBuilder b = new StringBuilder();
	for (String s : expected) {
		b.append(s);
		// b.append("\n");
	}
	try (ByteArrayInputStream bais = new ByteArrayInputStream(b.toString().getBytes())) {
		DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
		parser.setErrorHandler(new DefaultHandler());
		Element root = parser.parse(new InputSource(bais)).getDocumentElement();
		this.sre.setFromXML(root);
		assertTrue(this.sre.isStandalone());
		assertEquals(this.path, this.sre.getJarFile());
		assertEquals("Hello", this.sre.getName());
		assertEquals("io.sarl.Boot", this.sre.getMainClass());
	}
}
 
源代码3 项目: openjdk-jdk9   文件: UserController.java
/**
 * Checking Text content in XML file.
 * @see <a href="content/accountInfo.xml">accountInfo.xml</a>
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testMoreUserInfo() throws Exception {
    String xmlFile = XML_DIR + "accountInfo.xml";
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI);
    dbf.setNamespaceAware(true);
    dbf.setValidating(true);

    DocumentBuilder docBuilder = dbf.newDocumentBuilder();
    MyErrorHandler eh = new MyErrorHandler();
    docBuilder.setErrorHandler(eh);

    Document document = docBuilder.parse(xmlFile);
    Element account = (Element)document
            .getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "Account").item(0);
    String textContent = account.getTextContent();
    assertTrue(textContent.trim().regionMatches(0, "Rachel", 0, 6));
    assertEquals(textContent, "RachelGreen744");

    Attr accountID = account.getAttributeNodeNS(PORTAL_ACCOUNT_NS, "accountID");
    assertTrue(accountID.getTextContent().trim().equals("1"));

    assertFalse(eh.isAnyError());
}
 
源代码4 项目: openjdk-jdk9   文件: DocumentBuilderFactoryTest.java
/**
 * Test the default functionality of schema support method. In
 * this case the schema source property is set.
 * @throws Exception If any errors occur.
 */
@Test(dataProvider = "schema-source")
public void testCheckSchemaSupport2(Object schemaSource) throws Exception {
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setValidating(true);
        dbf.setNamespaceAware(true);
        dbf.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
                W3C_XML_SCHEMA_NS_URI);
        dbf.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaSource", schemaSource);
        MyErrorHandler eh = MyErrorHandler.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        db.setErrorHandler(eh);
        db.parse(new File(XML_DIR, "test1.xml"));
        assertFalse(eh.isErrorOccured());
    } finally {
        if (schemaSource instanceof Closeable) {
            ((Closeable) schemaSource).close();
        }
    }

}
 
源代码5 项目: openjdk-jdk9   文件: XMLSignatureInput.java
void convertToNodes() throws CanonicalizationException,
    ParserConfigurationException, IOException, SAXException {
    if (dfactory == null) {
        dfactory = DocumentBuilderFactory.newInstance();
        dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
        dfactory.setValidating(false);
        dfactory.setNamespaceAware(true);
    }
    DocumentBuilder db = dfactory.newDocumentBuilder();
    // select all nodes, also the comments.
    try {
        db.setErrorHandler(new com.sun.org.apache.xml.internal.security.utils.IgnoreAllErrorHandler());

        Document doc = db.parse(this.getOctetStream());
        this.subNode = doc;
    } catch (SAXException ex) {
        // if a not-wellformed nodeset exists, put a container around it...
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        baos.write("<container>".getBytes("UTF-8"));
        baos.write(this.getBytes());
        baos.write("</container>".getBytes("UTF-8"));

        byte result[] = baos.toByteArray();
        Document document = db.parse(new ByteArrayInputStream(result));
        this.subNode = document.getDocumentElement().getFirstChild().getFirstChild();
    } finally {
        if (this.inputOctetStreamProxy != null) {
            this.inputOctetStreamProxy.close();
        }
        this.inputOctetStreamProxy = null;
        this.bytes = null;
    }
}
 
源代码6 项目: DroidDLNA   文件: SOAPActionProcessorImpl.java
public void readBody(ActionRequestMessage requestMessage, ActionInvocation actionInvocation) throws UnsupportedDataException {

        log.fine("Reading body of " + requestMessage + " for: " + actionInvocation);
        if (log.isLoggable(Level.FINER)) {
            log.finer("===================================== SOAP BODY BEGIN ============================================");
            log.finer(requestMessage.getBodyString());
            log.finer("-===================================== SOAP BODY END ============================================");
        }

        String body = getMessageBody(requestMessage);
        try {

            DocumentBuilderFactory factory = createDocumentBuilderFactory();
            factory.setNamespaceAware(true);
            DocumentBuilder documentBuilder = factory.newDocumentBuilder();
            documentBuilder.setErrorHandler(this);

            Document d = documentBuilder.parse(new InputSource(new StringReader(body)));

            Element bodyElement = readBodyElement(d);

            readBodyRequest(d, bodyElement, requestMessage, actionInvocation);

        } catch (Exception ex) {
            throw new UnsupportedDataException("Can't transform message payload: " + ex, ex, body);
        }
    }
 
源代码7 项目: DroidDLNA   文件: GENAEventProcessorImpl.java
public void readBody(IncomingEventRequestMessage requestMessage) throws UnsupportedDataException {

        log.fine("Reading body of: " + requestMessage);
        if (log.isLoggable(Level.FINER)) {
            log.finer("===================================== GENA BODY BEGIN ============================================");
            log.finer(requestMessage.getBody().toString());
            log.finer("-===================================== GENA BODY END ============================================");
        }

        String body = getMessageBody(requestMessage);
        try {

            DocumentBuilderFactory factory = createDocumentBuilderFactory();
            factory.setNamespaceAware(true);
            DocumentBuilder documentBuilder = factory.newDocumentBuilder();
            documentBuilder.setErrorHandler(this);

            Document d = documentBuilder.parse(
                new InputSource(new StringReader(body))
            );

            Element propertysetElement = readPropertysetElement(d);

            readProperties(propertysetElement, requestMessage);

        } catch (Exception ex) {
            throw new UnsupportedDataException("Can't transform message payload: " + ex.getMessage(), ex, body);
        }
    }
 
源代码8 项目: TencentKona-8   文件: XMLSignatureInput.java
void convertToNodes() throws CanonicalizationException,
    ParserConfigurationException, IOException, SAXException {
    if (dfactory == null) {
        dfactory = DocumentBuilderFactory.newInstance();
        dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
        dfactory.setValidating(false);
        dfactory.setNamespaceAware(true);
    }
    DocumentBuilder db = dfactory.newDocumentBuilder();
    // select all nodes, also the comments.
    try {
        db.setErrorHandler(new com.sun.org.apache.xml.internal.security.utils.IgnoreAllErrorHandler());

        Document doc = db.parse(this.getOctetStream());
        this.subNode = doc;
    } catch (SAXException ex) {
        // if a not-wellformed nodeset exists, put a container around it...
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        baos.write("<container>".getBytes("UTF-8"));
        baos.write(this.getBytes());
        baos.write("</container>".getBytes("UTF-8"));

        byte result[] = baos.toByteArray();
        Document document = db.parse(new ByteArrayInputStream(result));
        this.subNode = document.getDocumentElement().getFirstChild().getFirstChild();
    } finally {
        if (this.inputOctetStreamProxy != null) {
            this.inputOctetStreamProxy.close();
        }
        this.inputOctetStreamProxy = null;
        this.bytes = null;
    }
}
 
源代码9 项目: totallylazy   文件: Xml.java
public static Document document(InputSource inputSource) {
    try {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        documentBuilder.setEntityResolver(ignoreEntities());
        documentBuilder.setErrorHandler(null);
        return documentBuilder.parse(inputSource);
    } catch (Exception e) {
        throw LazyException.lazyException(e);
    }
}
 
源代码10 项目: commons-vfs   文件: ParseXmlInZipTestCase.java
private DocumentBuilder newDocumentBuilder(final FileObject containerFile, final FileObject sourceFile,
        final String pathToXsdInZip) throws IOException {
    final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    final boolean validate = pathToXsdInZip != null;
    documentBuilderFactory.setValidating(validate);
    documentBuilderFactory.setNamespaceAware(true);
    if (validate) {
        documentBuilderFactory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
                "http://www.w3.org/2001/XMLSchema");
        @SuppressWarnings("resource")
        final FileObject schema = containerFile.resolveFile(pathToXsdInZip);
        if (schema.exists()) {
            documentBuilderFactory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaSource",
                    schema.getContent().getInputStream());
        } else {
            schema.close();
            throw new FileNotFoundException(schema.toString());
        }
    }
    DocumentBuilder documentBuilder = null;
    try {
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
        documentBuilder.setEntityResolver(new TestEntityResolver(containerFile, sourceFile));
    } catch (final ParserConfigurationException e) {
        throw new IOException("Cannot read Java Connector configuration: " + e, e);
    }
    documentBuilder.setErrorHandler(new TestErrorHandler(containerFile + " - " + sourceFile));
    return documentBuilder;
}
 
源代码11 项目: netbeans   文件: AntProjectSupport.java
/**
 * Make a DocumentBuilder object for use in this support.
 * Thread-safe, but of course the result is not.
 * @throws Exception for various reasons of configuration
 */
private static synchronized DocumentBuilder createDocumentBuilder() throws Exception {
    //DocumentBuilderFactory factory = (DocumentBuilderFactory)Class.forName(XERCES_DOCUMENT_BUILDER_FACTORY).newInstance();
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder documentBuilder = factory.newDocumentBuilder();
    documentBuilder.setErrorHandler(ErrHandler.DEFAULT);
    return documentBuilder;
}
 
源代码12 项目: JDKSourceCode1.8   文件: XMLSignatureInput.java
void convertToNodes() throws CanonicalizationException,
    ParserConfigurationException, IOException, SAXException {
    if (dfactory == null) {
        dfactory = DocumentBuilderFactory.newInstance();
        dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
        dfactory.setValidating(false);
        dfactory.setNamespaceAware(true);
    }
    DocumentBuilder db = dfactory.newDocumentBuilder();
    // select all nodes, also the comments.
    try {
        db.setErrorHandler(new com.sun.org.apache.xml.internal.security.utils.IgnoreAllErrorHandler());

        Document doc = db.parse(this.getOctetStream());
        this.subNode = doc;
    } catch (SAXException ex) {
        // if a not-wellformed nodeset exists, put a container around it...
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        baos.write("<container>".getBytes("UTF-8"));
        baos.write(this.getBytes());
        baos.write("</container>".getBytes("UTF-8"));

        byte result[] = baos.toByteArray();
        Document document = db.parse(new ByteArrayInputStream(result));
        this.subNode = document.getDocumentElement().getFirstChild().getFirstChild();
    } finally {
        if (this.inputOctetStreamProxy != null) {
            this.inputOctetStreamProxy.close();
        }
        this.inputOctetStreamProxy = null;
        this.bytes = null;
    }
}
 
源代码13 项目: blackduck-alert   文件: SamlMetaDataFileUpload.java
private ValidationResult validateXMLFile(File file) {

        try (InputStream fileInputStream = new FileInputStream(file)) {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setValidating(false);
            factory.setNamespaceAware(true);
            DocumentBuilder builder = factory.newDocumentBuilder();
            XMLErrorHandler errorHandler = new XMLErrorHandler();
            builder.setErrorHandler(errorHandler);
            builder.parse(new InputSource(fileInputStream));
        } catch (ParserConfigurationException | SAXException | IOException ex) {
            return ValidationResult.errors(String.format("XML file error: %s", ex.getMessage()));
        }
        return ValidationResult.success();
    }
 
源代码14 项目: hottub   文件: XMLSignatureInput.java
void convertToNodes() throws CanonicalizationException,
    ParserConfigurationException, IOException, SAXException {
    if (dfactory == null) {
        dfactory = DocumentBuilderFactory.newInstance();
        dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
        dfactory.setValidating(false);
        dfactory.setNamespaceAware(true);
    }
    DocumentBuilder db = dfactory.newDocumentBuilder();
    // select all nodes, also the comments.
    try {
        db.setErrorHandler(new com.sun.org.apache.xml.internal.security.utils.IgnoreAllErrorHandler());

        Document doc = db.parse(this.getOctetStream());
        this.subNode = doc;
    } catch (SAXException ex) {
        // if a not-wellformed nodeset exists, put a container around it...
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        baos.write("<container>".getBytes("UTF-8"));
        baos.write(this.getBytes());
        baos.write("</container>".getBytes("UTF-8"));

        byte result[] = baos.toByteArray();
        Document document = db.parse(new ByteArrayInputStream(result));
        this.subNode = document.getDocumentElement().getFirstChild().getFirstChild();
    } finally {
        if (this.inputOctetStreamProxy != null) {
            this.inputOctetStreamProxy.close();
        }
        this.inputOctetStreamProxy = null;
        this.bytes = null;
    }
}
 
/**
 * Validate the given stream and return a valid DOM document for parsing.
 */
protected Document buildDocument(ErrorHandler handler, InputStream stream)
		throws ParserConfigurationException, SAXException, IOException {

	DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
	dbf.setNamespaceAware(true);
	DocumentBuilder parser = dbf.newDocumentBuilder();
	parser.setErrorHandler(handler);
	return parser.parse(stream);
}
 
源代码16 项目: wisp   文件: ConfigParser.java
public Map<String, TableConfig> parse(InputStream xmlPath) throws Exception {

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        factory.setValidating(true);
        factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
                "http://www.w3.org/2001/XMLSchema");

        Document document = null;
        DocumentBuilder docBuilder = null;
        docBuilder = factory.newDocumentBuilder();
        DefaultHandler handler = new DefaultHandler();
        docBuilder.setEntityResolver(handler);
        docBuilder.setErrorHandler(handler);

        document = docBuilder.parse(xmlPath);

        Element rootEl = document.getDocumentElement();

        NodeList children = rootEl.getChildNodes();

        BaseConfig currentBaseConfig = null;
        Map<String, TableConfig> allTableConfigMap = new HashMap<String, TableConfig>();
        for (int i = 0; i < children.getLength(); i++) {
            Node node = children.item(i);
            if (node instanceof Element) {
                Element element = (Element) node;

                if (elementNameMatch(element, "base")) {

                    currentBaseConfig = parseBase(element);

                } else if (elementNameMatch(element, "dbs")) {

                    allTableConfigMap = parseDbs(element, currentBaseConfig);
                }

            }
        }

        return allTableConfigMap;
    }
 
源代码17 项目: nifi   文件: FlowParser.java
/**
 * Extracts the root group id from the flow configuration file provided in nifi.properties, and extracts
 * the root group input ports and output ports, and their access controls.
 *
 */
public FlowInfo parse(final File flowConfigurationFile) {
    if (flowConfigurationFile == null) {
        logger.debug("Flow Configuration file was null");
        return null;
    }

    // if the flow doesn't exist or is 0 bytes, then return null
    final Path flowPath = flowConfigurationFile.toPath();
    try {
        if (!Files.exists(flowPath) || Files.size(flowPath) == 0) {
            logger.warn("Flow Configuration does not exist or was empty");
            return null;
        }
    } catch (IOException e) {
        logger.error("An error occurred determining the size of the Flow Configuration file");
        return null;
    }

    // otherwise create the appropriate input streams to read the file
    try (final InputStream in = Files.newInputStream(flowPath, StandardOpenOption.READ);
         final InputStream gzipIn = new GZIPInputStream(in)) {

        final byte[] flowBytes = IOUtils.toByteArray(gzipIn);
        if (flowBytes == null || flowBytes.length == 0) {
            logger.warn("Could not extract root group id because Flow Configuration File was empty");
            return null;
        }

        // create validating document builder
        final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        docFactory.setNamespaceAware(true);
        docFactory.setSchema(flowSchema);

        // parse the flow
        final DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        docBuilder.setErrorHandler(new LoggingXmlParserErrorHandler("Flow Configuration", logger));
        final Document document = docBuilder.parse(new ByteArrayInputStream(flowBytes));

        // extract the root group id
        final Element rootElement = document.getDocumentElement();

        final Element rootGroupElement = (Element) rootElement.getElementsByTagName("rootGroup").item(0);
        if (rootGroupElement == null) {
            logger.warn("rootGroup element not found in Flow Configuration file");
            return null;
        }

        final Element rootGroupIdElement = (Element) rootGroupElement.getElementsByTagName("id").item(0);
        if (rootGroupIdElement == null) {
            logger.warn("id element not found under rootGroup in Flow Configuration file");
            return null;
        }

        final String rootGroupId = rootGroupIdElement.getTextContent();

        final List<PortDTO> ports = new ArrayList<>();
        ports.addAll(getPorts(rootGroupElement, "inputPort"));
        ports.addAll(getPorts(rootGroupElement, "outputPort"));

        return new FlowInfo(rootGroupId, ports);

    } catch (final SAXException | ParserConfigurationException | IOException ex) {
        logger.error("Unable to parse flow {} due to {}", new Object[] { flowPath.toAbsolutePath(), ex });
        return null;
    }
}
 
源代码18 项目: wisp   文件: ConfigParser.java
/**
 * parse data
 *
 * @param xmlPath
 *
 * @return
 *
 * @throws Exception
 */
public static InitDbConfig parse(InputStream xmlPath) throws Exception {

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    factory.setValidating(true);
    factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
            "http://www.w3.org/2001/XMLSchema");

    Document document = null;
    DocumentBuilder docBuilder = null;
    docBuilder = factory.newDocumentBuilder();
    DefaultHandler handler = new DefaultHandler();
    docBuilder.setEntityResolver(handler);
    docBuilder.setErrorHandler(handler);

    document = docBuilder.parse(xmlPath);

    List<String> schemaList = new ArrayList<>();
    List<String> dataList = new ArrayList<>();

    Element rootEl = document.getDocumentElement();
    NodeList children = rootEl.getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
        Node node = children.item(i);
        if (node instanceof Element) {
            Element element = (Element) node;

            if (elementNameMatch(element, "initialize-database")) {

                schemaList = parseSchemaList(element);

            } else if (elementNameMatch(element, "initialize-data")) {

                dataList = parseDataList(element);
            }

        }
    }

    InitDbConfig initDbConfig = new InitDbConfig();
    initDbConfig.setDataFileList(dataList);
    initDbConfig.setSchemaFileList(schemaList);

    return initDbConfig;
}
 
源代码19 项目: tracecompass   文件: CustomTxtTraceDefinition.java
@Override
public void save(String path) {
    try {
        DocumentBuilder db = XmlUtils.newSafeDocumentBuilderFactory().newDocumentBuilder();

        // The following allows xml parsing without access to the dtd
        db.setEntityResolver(createEmptyEntityResolver());

        // The following catches xml parsing exceptions
        db.setErrorHandler(createErrorHandler());

        Document doc = null;
        File file = new File(path);
        if (file.canRead()) {
            doc = db.parse(file);
            if (!doc.getDocumentElement().getNodeName().equals(CUSTOM_TXT_TRACE_DEFINITION_ROOT_ELEMENT)) {
                Activator.logError(String.format("Error saving CustomTxtTraceDefinition: path=%s is not a valid custom parser file", path)); //$NON-NLS-1$
                return;
            }
        } else {
            doc = db.newDocument();
            Node node = doc.createElement(CUSTOM_TXT_TRACE_DEFINITION_ROOT_ELEMENT);
            doc.appendChild(node);
        }

        Element root = doc.getDocumentElement();

        Element oldDefinitionElement = findDefinitionElement(root, categoryName, definitionName);
        if (oldDefinitionElement != null) {
            root.removeChild(oldDefinitionElement);
        }
        Element definitionElement = doc.createElement(DEFINITION_ELEMENT);
        root.appendChild(definitionElement);
        definitionElement.setAttribute(CATEGORY_ATTRIBUTE, categoryName);
        definitionElement.setAttribute(NAME_ATTRIBUTE, definitionName);

        if (timeStampOutputFormat != null && !timeStampOutputFormat.isEmpty()) {
            Element formatElement = doc.createElement(TIME_STAMP_OUTPUT_FORMAT_ELEMENT);
            definitionElement.appendChild(formatElement);
            formatElement.appendChild(doc.createTextNode(timeStampOutputFormat));
        }

        if (inputs != null) {
            for (InputLine inputLine : inputs) {
                definitionElement.appendChild(createInputLineElement(inputLine, doc));
            }
        }

        if (outputs != null) {
            for (OutputColumn output : outputs) {
                Element outputColumnElement = doc.createElement(OUTPUT_COLUMN_ELEMENT);
                definitionElement.appendChild(outputColumnElement);
                outputColumnElement.setAttribute(TAG_ATTRIBUTE, output.tag.name());
                outputColumnElement.setAttribute(NAME_ATTRIBUTE, output.name);
            }
        }

        Transformer transformer = XmlUtils.newSecureTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$

        // initialize StreamResult with File object to save to file
        StreamResult result = new StreamResult(new StringWriter());
        DOMSource source = new DOMSource(doc);
        transformer.transform(source, result);
        String xmlString = result.getWriter().toString();

        try (FileWriter writer = new FileWriter(file);) {
            writer.write(xmlString);
        }

        TmfTraceType.addCustomTraceType(CustomTxtTrace.class, categoryName, definitionName);

    } catch (ParserConfigurationException | TransformerFactoryConfigurationError | TransformerException | IOException | SAXException e) {
        Activator.logError("Error saving CustomTxtTraceDefinition: path=" + path, e); //$NON-NLS-1$
    }
}
 
源代码20 项目: ehcache3   文件: DomUtil.java
public static DocumentBuilder createAndGetDocumentBuilder(Collection<Source> schemaSources) throws SAXException, ParserConfigurationException {
  DocumentBuilderFactory factory = createAndGetFactory(schemaSources);
  DocumentBuilder documentBuilder = factory.newDocumentBuilder();
  documentBuilder.setErrorHandler(new TransformationErrorHandler());
  return documentBuilder;
}