Java 类javax.xml.transform.dom.DOMSource 实例源码

项目:openjdk-jdk10    文件:DTMManagerDefault.java   
/**
 * Method createDocumentFragment
 *
 *
 * NEEDSDOC (createDocumentFragment) @return
 */
synchronized public DTM createDocumentFragment()
{

  try
  {
    DocumentBuilderFactory dbf = FactoryImpl.getDOMFactory(super.useServicesMechnism());
    dbf.setNamespaceAware(true);

    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.newDocument();
    Node df = doc.createDocumentFragment();

    return getDTM(new DOMSource(df), true, null, false, false);
  }
  catch (Exception e)
  {
    throw new DTMException(e);
  }
}
项目:lams    文件:GetResponse.java   
/**
 * Creates the XML representation of this get response. The underlying DOM
 * document will transformed to a string.
 * 
 * @throws RuntimeException
 *             if creation failed
 * @return XML representation of this get response
 */
@Override
public String toString() {
    document.getDocumentElement().normalize();
    TransformerFactory factory = TransformerFactory.newInstance();

    StringWriter sw = new StringWriter();

    try {
        Transformer transformer = factory.newTransformer();

        DOMSource source = new DOMSource(document);
        StreamResult result = new StreamResult(sw);

        transformer.transform(source, result);
    } catch (TransformerException e) {
        throw new RuntimeException(e);
    }

    return sw.toString();
}
项目:openjdk-jdk10    文件:Sources.java   
@DataProvider(name = "emptySources")
public Object[][] getSources() throws URISyntaxException {

    return new Object[][]{
        {new DOMSource()},
        {new DOMSource(getDocument())},
        {new SAXSource()},
        {new SAXSource(new InputSource(new StringReader("")))},
        {new SAXSource(getXMLReader(), new InputSource(new StringReader("")))},
        {new StreamSource()},
        {new StreamSource(new ByteArrayInputStream("".getBytes()))},
        {new StreamSource(new StringReader(""))},
        {new StreamSource(new StringReader(""), null)},
        {new StreamSource((String) null)}
    };
}
项目:openjdk-jdk10    文件:CatalogSupport4.java   
@DataProvider(name = "data_ValidatorA")
public Object[][] getDataValidator() {
    DOMSource ds = getDOMSource(xml_val_test, xml_val_test_id, true, true, xml_catalog);

    SAXSource ss = new SAXSource(new InputSource(xml_val_test));
    ss.setSystemId(xml_val_test_id);

    StAXSource stax = getStaxSource(xml_val_test, xml_val_test_id, true, true, xml_catalog);
    StAXSource stax1 = getStaxSource(xml_val_test, xml_val_test_id, true, true, xml_catalog);

    StreamSource source = new StreamSource(new File(xml_val_test));

    return new Object[][]{
        // use catalog
        {true, false, true, ds, null, null, xml_catalog, null},
        {false, true, true, ds, null, null, null, xml_catalog},
        {true, false, true, ss, null, null, xml_catalog, null},
        {false, true, true, ss, null, null, null, xml_catalog},
        {true, false, true, stax, null, null, xml_catalog, xml_catalog},
        {false, true, true, stax1, null, null, xml_catalog, xml_catalog},
        {true, false, true, source, null, null, xml_catalog, null},
        {false, true, true, source, null, null, null, xml_catalog},
    };
}
项目:featurea    文件:XMLOutputVisitor.java   
private void doTransform(String sXSL, OutputStream os) throws javax.xml.transform.TransformerConfigurationException, javax.xml.transform.TransformerException {
    // create the transformerfactory & transformer instance
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer t = tf.newTransformer();

    if (null == sXSL) {
        t.transform(new DOMSource(doc), new StreamResult(os));
        return;
    }

    try {
        Transformer finalTransformer = tf.newTransformer(new StreamSource(sXSL));
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        BufferedOutputStream bos = new BufferedOutputStream(baos);
        t.transform(new DOMSource(doc), new StreamResult(bos));
        bos.flush();
        StreamSource xmlSource = new StreamSource(new BufferedInputStream(new ByteArrayInputStream(baos.toByteArray())));
        finalTransformer.transform(xmlSource, new StreamResult(os));
    } catch (IOException ioe) {
        throw new javax.xml.transform.TransformerException(ioe);
    }
}
项目:javaide    文件:FormatFactory.java   
private static String formatXml(Context context, String src) throws TransformerException,
        ParserConfigurationException, IOException, SAXException {
    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document doc = builder.parse(new InputSource(new StringReader(src)));

    AppSetting setting = new AppSetting(context);
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", setting.getTab().length() + "");
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");

    //initialize StreamResult with File object to save to file
    StreamResult result = new StreamResult(new StringWriter());
    DOMSource source = new DOMSource(doc);
    transformer.transform(source, result);
    return result.getWriter().toString();
}
项目:Equella    文件:XmlDocument.java   
public static String xmlToString(Node node)
{
    try
    {
        Source source = new DOMSource(node);
        StringWriter writer = new StringWriter();
        Result result = new StreamResult(writer);
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.transform(source, result);
        return writer.toString();
    }
    catch( Exception e )
    {
        throw new RuntimeException(e);
    }
}
项目:springboot-shiro-cas-mybatis    文件:AbstractSamlObjectBuilder.java   
/**
 * Marshal the saml xml object to raw xml.
 *
 * @param object the object
 * @param writer the writer
 * @return the xml string
 */
public String marshalSamlXmlObject(final XMLObject object, final StringWriter writer)  {
    try {
        final MarshallerFactory marshallerFactory = XMLObjectProviderRegistrySupport.getMarshallerFactory();
        final Marshaller marshaller = marshallerFactory.getMarshaller(object);
        if (marshaller == null) {
            throw new IllegalArgumentException("Cannot obtain marshaller for object " + object.getElementQName());
        }
        final Element element = marshaller.marshall(object);
        element.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", SAMLConstants.SAML20_NS);
        element.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xenc", "http://www.w3.org/2001/04/xmlenc#");

        final TransformerFactory transFactory = TransformerFactory.newInstance();
        final Transformer transformer = transFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.transform(new DOMSource(element), new StreamResult(writer));
        return writer.toString();
    } catch (final Exception e) {
        throw new IllegalStateException("An error has occurred while marshalling SAML object to xml", e);
    }
}
项目:openjdk-jdk10    文件:TfClearParamTest.java   
/**
 * Obtains transformer's parameter whose initiated with a dom source with
 * the a name that set before. Value should be same as set one.
 * @throws Exception If any errors occur.
 */
@Test
public void clear09() throws Exception {
    TransformerFactory tfactory = TransformerFactory.newInstance();

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document document = db.parse(new File(XSL_FILE));
    DOMSource domSource = new DOMSource((Node)document);

    Transformer transformer = tfactory.newTransformer(domSource);

    transformer.setParameter(LONG_PARAM_NAME, PARAM_VALUE);
    assertEquals(transformer.getParameter(LONG_PARAM_NAME), PARAM_VALUE);
}
项目:openjdk-jdk10    文件:Bug4971605.java   
@Test
public void test1() throws Exception {
    String xsd = "<?xml version='1.0'?>\n" + "<schema xmlns='http://www.w3.org/2001/XMLSchema'\n" + "        xmlns:test='jaxp13_test1'\n"
            + "        targetNamespace='jaxp13_test1'\n" + "        elementFormDefault='qualified'>\n" + "    <element name='test'/>\n" + "</schema>\n";

    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    docBuilderFactory.setNamespaceAware(true);
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();

    Node document = docBuilder.parse(new InputSource(new StringReader(xsd)));
    Assert.assertNotNull(document);

    SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    Schema schema = schemaFactory.newSchema(new Source[] { new DOMSource(document) });
    Assert.assertNotNull(schema, "Failed: newSchema returned null.");
}
项目:Tarski    文件:GraphBuilder.java   
/**
 * Writes given xmlDocument to xml file.
 *
 * @param xmlDocument
 */
@SuppressWarnings("unused")
private void writeXml(final Document xmlDocument) {
  Transformer transformer;
  try {
    transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "3");
    final DOMSource source = new DOMSource(xmlDocument);
    // final StreamResult console =
    // new StreamResult(new File("C:/Users/emre.kirmizi/Desktop/out.xml"));
    final StreamResult console =
        new StreamResult(new File("C:/Users/anil.ozturk/Desktop/out.xml"));
    transformer.transform(source, console);
  } catch (TransformerFactoryConfigurationError | TransformerException e) {
    e.printStackTrace();
  }
}
项目:OpenJSharp    文件:UnmarshallerImpl.java   
@Override
public <T> JAXBElement<T> unmarshal( Source source, Class<T> expectedType ) throws JAXBException {
    if (source instanceof SAXSource) {
        SAXSource ss = (SAXSource) source;

        XMLReader locReader = ss.getXMLReader();
        if (locReader == null) {
            locReader = getXMLReader();
        }

        return unmarshal(locReader, ss.getInputSource(), expectedType);
    }
    if (source instanceof StreamSource) {
        return unmarshal(getXMLReader(), streamSourceToInputSource((StreamSource) source), expectedType);
    }
    if (source instanceof DOMSource) {
        return unmarshal(((DOMSource) source).getNode(), expectedType);
    }

    // we don't handle other types of Source
    throw new IllegalArgumentException();
}
项目:page-content-tester    文件:XmlErrorHandler.java   
@SneakyThrows
public void validateXml(String xsdPath, boolean namespaceAware, String schemaLanguage, String pageBody) {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    factory.setNamespaceAware(namespaceAware);

    DocumentBuilder builder = factory.newDocumentBuilder();
    org.w3c.dom.Document document = builder.parse(new InputSource(new StringReader(pageBody)));

    SchemaFactory schemaFactory = SchemaFactory.newInstance(schemaLanguage);
    Source schemaSource = new StreamSource(getClass().getResourceAsStream(xsdPath));

    Schema schema = schemaFactory.newSchema(schemaSource);
    Validator validator = schema.newValidator();
    Source source = new DOMSource(document);
    validator.setErrorHandler(new XmlErrorHandler());
    validator.validate(source);
}
项目:framework    文件:XmlUtils.java   
/**
 * Converts the Node/Document/Element instance to XML payload.
 *
 * @param node the node/document/element instance to convert
 * @return the XML payload representing the node/document/element
 * @throws AlipayApiException problem converting XML to string
 */
public static String nodeToString(Node node) throws AlipayApiException {
    String payload = null;

    try {
        Transformer tf = TransformerFactory.newInstance().newTransformer();

        Properties props = tf.getOutputProperties();
        props.setProperty(OutputKeys.INDENT, LOGIC_YES);
        props.setProperty(OutputKeys.ENCODING, DEFAULT_ENCODE);
        tf.setOutputProperties(props);

        StringWriter writer = new StringWriter();
        tf.transform(new DOMSource(node), new StreamResult(writer));
        payload = writer.toString();
        payload = payload.replaceAll(REG_INVALID_CHARS, " ");
    } catch (TransformerException e) {
        throw new AlipayApiException("XML_TRANSFORM_ERROR", e);
    }

    return payload;
}
项目:OpenDiabetes    文件:JDBCSQLXML.java   
/**
 * Returns a Source for reading the XML value designated by this SQLXML
 * instance. <p>
 *
 * @param sourceClass The class of the source, or null.  If null, then a
 *      DOMSource is returned.
 * @return a Source for reading the XML value.
 * @throws SQLException if there is an error processing the XML value
 *   or if the given <tt>sourceClass</tt> is not supported.
 */
protected <T extends Source>T getSourceImpl(
        Class<T> sourceClass) throws SQLException {

    if (JAXBSource.class.isAssignableFrom(sourceClass)) {

        // Must go first presently, since JAXBSource extends SAXSource
        // (purely as an implementation detail) and it's not possible
        // to instantiate a valid JAXBSource with a Zero-Args
        // constructor(or any subclass thereof, due to the finality of
        // its private marshaller and context object attributes)
        // FALL THROUGH... will throw an exception
    } else if (StreamSource.class.isAssignableFrom(sourceClass)) {
        return createStreamSource(sourceClass);
    } else if ((sourceClass == null)
               || DOMSource.class.isAssignableFrom(sourceClass)) {
        return createDOMSource(sourceClass);
    } else if (SAXSource.class.isAssignableFrom(sourceClass)) {
        return createSAXSource(sourceClass);
    } else if (StAXSource.class.isAssignableFrom(sourceClass)) {
        return createStAXSource(sourceClass);
    }

    throw JDBCUtil.invalidArgument("sourceClass: " + sourceClass);
}
项目:dev-courses    文件:JDBCSQLXML.java   
/**
 * Returns a Source for reading the XML value designated by this SQLXML
 * instance. <p>
 *
 * @param sourceClass The class of the source, or null.  If null, then a
 *      DOMSource is returned.
 * @return a Source for reading the XML value.
 * @throws SQLException if there is an error processing the XML value
 *   or if the given <tt>sourceClass</tt> is not supported.
 */
protected <T extends Source>T getSourceImpl(
        Class<T> sourceClass) throws SQLException {

    if (JAXBSource.class.isAssignableFrom(sourceClass)) {

        // Must go first presently, since JAXBSource extends SAXSource
        // (purely as an implmentation detail) and it's not possible
        // to instantiate a valid JAXBSource with a Zero-Args
        // constructor(or any subclass thereof, due to the finality of
        // its private marshaller and context object attrbutes)
        // FALL THROUGH... will throw an exception
    } else if (StreamSource.class.isAssignableFrom(sourceClass)) {
        return createStreamSource(sourceClass);
    } else if ((sourceClass == null)
               || DOMSource.class.isAssignableFrom(sourceClass)) {
        return createDOMSource(sourceClass);
    } else if (SAXSource.class.isAssignableFrom(sourceClass)) {
        return createSAXSource(sourceClass);
    } else if (StAXSource.class.isAssignableFrom(sourceClass)) {
        return createStAXSource(sourceClass);
    }

    throw JDBCUtil.invalidArgument("sourceClass: " + sourceClass);
}
项目:oasp-tutorial-sources    文件:AccessControlSchemaXmlValidationTest.java   
/**
 * Tests if the access-control-schema.xml is valid.
 *
 * @throws ParserConfigurationException If a DocumentBuilder cannot be created which satisfies the configuration
 *         requested.
 * @throws IOException If any IO errors occur.
 * @throws SAXException If an error occurs during the validation.
 */
@Test
public void validateAccessControllSchema() throws ParserConfigurationException, SAXException, IOException {

  // parse an XML document into a DOM tree
  DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
  String xmlPath = getClass().getResource("/config/app/security/access-control-schema.xml").getPath();
  Document document = parser.parse(new File(xmlPath));

  // create a SchemaFactory capable of understanding WXS schemas
  SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

  // load a WXS schema, represented by a Schema instance
  URL schemaPath = getClass().getResource("/io/oasp/module/security/access-control-schema.xsd");
  Schema schema = factory.newSchema(schemaPath);

  // create a Validator instance, which can be used to validate an instance document
  Validator validator = schema.newValidator();

  // validate the DOM tree
  validator.validate(new DOMSource(document));
}
项目:openjdk-jdk10    文件:TransformerTest.java   
/**
 * This tests getOutputProperties() method of Transformer.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void transformer05() throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document document = db.parse(new File(TEST_XSL));
    DOMSource domSource = new DOMSource(document);

    Transformer transformer = TransformerFactory.newInstance().
            newTransformer(domSource);
    Properties prop = transformer.getOutputProperties();

    assertEquals(prop.getProperty("indent"), "yes");
    assertEquals(prop.getProperty("method"), "xml");
    assertEquals(prop.getProperty("encoding"), "UTF-8");
    assertEquals(prop.getProperty("standalone"), "no");
    assertEquals(prop.getProperty("version"), "1.0");
    assertEquals(prop.getProperty("omit-xml-declaration"), "no");
}
项目:sstore-soft    文件:JDBCSQLXML.java   
/**
 * Returns a Source for reading the XML value designated by this SQLXML
 * instance. <p>
 *
 * @param sourceClass The class of the source, or null.  If null, then a
 *      DOMSource is returned.
 * @return a Source for reading the XML value.
 * @throws SQLException if there is an error processing the XML value
 *   or if the given <tt>sourceClass</tt> is not supported.
 */
protected <T extends Source>T getSourceImpl(
        Class<T> sourceClass) throws SQLException {

    if (JAXBSource.class.isAssignableFrom(sourceClass)) {

        // Must go first presently, since JAXBSource extends SAXSource
        // (purely as an implmentation detail) and it's not possible
        // to instantiate a valid JAXBSource with a Zero-Args
        // constructor(or any subclass thereof, due to the finality of
        // its private marshaller and context object attrbutes)
        // FALL THROUGH... will throw an exception
    } else if (StreamSource.class.isAssignableFrom(sourceClass)) {
        return createStreamSource(sourceClass);
    } else if ((sourceClass == null)
               || DOMSource.class.isAssignableFrom(sourceClass)) {
        return createDOMSource(sourceClass);
    } else if (SAXSource.class.isAssignableFrom(sourceClass)) {
        return createSAXSource(sourceClass);
    } else if (StAXSource.class.isAssignableFrom(sourceClass)) {
        return createStAXSource(sourceClass);
    }

    throw Util.invalidArgument("sourceClass: " + sourceClass);
}
项目:Progetto-C    文件:ParticleIO.java   
/**
 * Save a single emitter to the XML file
 * 
 * @param out
 *            The location to which we should save
 * @param emitter
 *            The emitter to store to the XML file
 * @throws IOException
 *             Indicates a failure to write or encode the XML
 */
public static void saveEmitter(OutputStream out, ConfigurableEmitter emitter)
        throws IOException {
    try {
        DocumentBuilder builder = DocumentBuilderFactory.newInstance()
                .newDocumentBuilder();
        Document document = builder.newDocument();

        document.appendChild(emitterToElement(document, emitter));
        Result result = new StreamResult(new OutputStreamWriter(out,
                "utf-8"));
        DOMSource source = new DOMSource(document);

        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer xformer = factory.newTransformer();
        xformer.setOutputProperty(OutputKeys.INDENT, "yes");

        xformer.transform(source, result);
    } catch (Exception e) {
        Log.error(e);
        throw new IOException("Failed to save emitter");
    }
}
项目:openjdk-jdk10    文件:DOMForest.java   
/**
 * Checks the correctness of the XML Schema documents and return true
 * if it's OK.
 *
 * <p>
 * This method performs a weaker version of the tests where error messages
 * are provided without line number information. So whenever possible
 * use {@link SchemaConstraintChecker}.
 *
 * @see SchemaConstraintChecker
 */
public boolean checkSchemaCorrectness(ErrorReceiver errorHandler) {
    try {
        boolean disableXmlSecurity = false;
        if (options != null) {
            disableXmlSecurity = options.disableXmlSecurity;
        }
        SchemaFactory sf = XmlFactory.createSchemaFactory(W3C_XML_SCHEMA_NS_URI, disableXmlSecurity);
        ErrorReceiverFilter filter = new ErrorReceiverFilter(errorHandler);
        sf.setErrorHandler(filter);
        Set<String> roots = getRootDocuments();
        Source[] sources = new Source[roots.size()];
        int i=0;
        for (String root : roots) {
            sources[i++] = new DOMSource(get(root),root);
        }
        sf.newSchema(sources);
        return !filter.hadError();
    } catch (SAXException e) {
        // the errors should have been reported
        return false;
    }
}
项目:DeskChan    文件:CharacterPreset.java   
public void saveInFile(Path path) throws IOException {
    try {
        Document doc = DocumentBuilderFactory.newInstance()
                                             .newDocumentBuilder()
                                             .parse(new InputSource(new StringReader(XML.toString(toJSON()))));

        Transformer t = TransformerFactory.newInstance().newTransformer();
        t.setOutputProperty(javax.xml.transform.OutputKeys.INDENT, "yes");
        t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        t.setOutputProperty(javax.xml.transform.OutputKeys.OMIT_XML_DECLARATION, "yes");
        OutputStreamWriter stream = new OutputStreamWriter(new FileOutputStream(path.resolve("saved.preset").toFile()), "UTF-8");
        t.transform(new DOMSource(doc), new StreamResult(stream));
    } catch(Exception ex){
        Main.log(ex);
        Main.log("Error while writing preset file");
    }
}
项目:lams    文件:UpdateWarTask.java   
/**
    * Writes the modified web.xml back out to war file
    * 
    * @param doc
    *            The application.xml DOM Document
    * @throws org.apache.tools.ant.DeployException
    *             in case of any problems
    */
   protected void writeWebXml(final Document doc, final OutputStream outputStream) throws DeployException {
try {
    doc.normalize();

    // Prepare the DOM document for writing
    DOMSource source = new DOMSource(doc);

    // Prepare the output file
    StreamResult result = new StreamResult(outputStream);

    // Write the DOM document to the file
    // Get Transformer
    Transformer xformer = TransformerFactory.newInstance().newTransformer();
    // Write to a file
    xformer.transform(source, result);
} catch (TransformerException tex) {
    throw new DeployException("Error writing out modified web xml ", tex);
}
   }
项目:KeYExperienceReport    文件:SPL2OpltionGenerator.java   
private static void writeOut(Document doc) throws TransformerException {
    TransformerFactory transformerFactory = TransformerFactory
            .newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    transformer.setOutputProperty(OutputKeys.STANDALONE, "no");
    DOMSource source = new DOMSource(doc);
    File f = new File("splFile.xml");
    f.delete();
    StreamResult result = new StreamResult(f);

    // Output to console for testing
    // StreamResult result = new StreamResult(System.out);

    transformer.transform(source, result);

    System.out.println("File saved!");

}
项目:wechat-pay-sdk    文件:XmlUtils.java   
/**
 * Converts the Node/Element instance to XML payload.
 *
 * @param node the node/element instance to convert
 * @return the XML payload representing the node/element
 * @throws WXPayApiException problem converting XML to string
 */
public static String childNodeToString(Node node) throws WXPayApiException {
    String payload = null;

    try {
        Transformer tf = TransformerFactory.newInstance().newTransformer();

        Properties props = tf.getOutputProperties();
        props.setProperty(OutputKeys.OMIT_XML_DECLARATION, LOGIC_YES);
        tf.setOutputProperties(props);

        StringWriter writer = new StringWriter();
        tf.transform(new DOMSource(node), new StreamResult(writer));
        payload = writer.toString();
        payload = payload.replaceAll(REG_INVALID_CHARS, " ");
    } catch (TransformerException e) {
        throw new WXPayApiException("XML_TRANSFORM_ERROR", e);
    }

    return payload;
}
项目:OperatieBRP    文件:SynchronisatieWebServiceImpl.java   
/**
 * Handelt het verzoek af.
 * @param request het verzoek
 * @return het response.
 */
@Bedrijfsregel(Regel.R1978)
@Bedrijfsregel(Regel.R1979)
@Override
public final DOMSource invoke(final DOMSource request) {
    Thread.currentThread().setName("Synchronisatie Service");
    LOGGER.debug("SynchronisatieService aangeroepen");
    try {
        schemaValidatorService.valideer(request, SCHEMA);
    } catch (SchemaValidatorService.SchemaValidatieException schemaValidatieException) {
        LOGGER.debug("SynchronisatieService aangeroepen met invalide xml", schemaValidatieException);
        throw new Fault(schemaValidatieException.getCause());
    }
    BrpNu.set(DatumUtil.nuAlsZonedDateTime());
    return AlgemeneFoutHandler
            .doeBijFout(e1 -> {
                LOGGER.error("Algemene fout", e1);
                throw new WebServiceException("Er is iets fout gegaan bij het verwerken van het verzoek.");
            }).voerUit(() -> maakResponse(request));
}
项目:openjdk-jdk10    文件:Bug6531160.java   
@Test
public void testDOMLevel1Validation() throws Exception {
    SchemaFactory fact = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = fact.newSchema(new StreamSource(new StringReader(XSD)));
    DocumentBuilderFactory docfact = DocumentBuilderFactory.newInstance();
    docfact.setNamespaceAware(true);

    Document doc = docfact.newDocumentBuilder().newDocument();
    doc.appendChild(doc.createElement("root"));

    try {
        schema.newValidator().validate(new DOMSource(doc));
    } catch (SAXParseException e) {
        Assert.fail("Validation failed: " + e.getMessage());
    }
}
项目:javaide    文件:MergerXmlUtils.java   
/**
 * Outputs the given XML {@link Document} to the file {@code outFile}.
 *
 * TODO right now reformats the document. Needs to output as-is, respecting white-space.
 *
 * @param doc The document to output. Must not be null.
 * @param outFile The {@link File} where to write the document.
 * @param log A log in case of error.
 * @return True if the file was written, false in case of error.
 */
static boolean printXmlFile(
        @NonNull Document doc,
        @NonNull File outFile,
        @NonNull IMergerLog log) {
    // Quick thing based on comments from http://stackoverflow.com/questions/139076
    try {
        Transformer tf = TransformerFactory.newInstance().newTransformer();
        tf.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");         //$NON-NLS-1$
        tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");                   //$NON-NLS-1$
        tf.setOutputProperty(OutputKeys.INDENT, "yes");                       //$NON-NLS-1$
        tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount",     //$NON-NLS-1$
                             "4");                                            //$NON-NLS-1$
        tf.transform(new DOMSource(doc), new StreamResult(outFile));
        return true;
    } catch (TransformerException e) {
        log.error(Severity.ERROR,
                new FileAndLine(outFile.getName(), 0),
                "Failed to write XML file: %1$s",
                e.toString());
        return false;
    }
}
项目:openjdk-jdk10    文件:URIResolverTest.java   
/**
 * This is to test the URIResolver.resolve() method when there is an error
 * in the file.
 *
 * @throws Exception If any errors occur.
 */
@Test
public static void docResolver01() throws Exception {
    try (FileInputStream fis = new FileInputStream(XML_DIR + "doctest.xsl")) {
        URIResolverTest resolver = new URIResolverTest("temp/colors.xml", SYSTEM_ID);
        StreamSource streamSource = new StreamSource(fis);
        streamSource.setSystemId(SYSTEM_ID);

        Transformer transformer = TransformerFactory.newInstance().newTransformer(streamSource);
        transformer.setURIResolver(resolver);

        File f = new File(XML_DIR + "myFake.xml");
        Document document = DocumentBuilderFactory.newInstance().
                newDocumentBuilder().parse(f);

        // Use a Transformer for output
        DOMSource source = new DOMSource(document);
        StreamResult result = new StreamResult(System.err);
        // No exception is expected because resolver resolve wrong URI.
        transformer.transform(source, result);
    }
}
项目:xmlrss    文件:AbstractXMLRSSTest.java   
protected void validateXSD(Document signedDoc) throws SAXException, IOException {
    NodeList nodeList = signedDoc.getElementsByTagNameNS(RedactableXMLSignature.XML_NAMESPACE, "Signature");
    assertEquals(1, nodeList.getLength());

    Node signature = nodeList.item(0);
    NodeList childNodes = signature.getChildNodes();
    int actualNodes = 0;
    for (int i = 0; i < childNodes.getLength(); i++) {
        if (childNodes.item(i).getNodeType() == Node.ELEMENT_NODE) {
            ++actualNodes;
        }
    }
    assertEquals(3, actualNodes);

    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = schemaFactory.newSchema(new File("xmlrss_schema.xsd"));
    Validator validator = schema.newValidator();
    validator.validate(new DOMSource(signature));
}
项目:ProyectoPacientes    文件:JDBC4MysqlSQLXML.java   
protected String domSourceToString() throws SQLException {
    try {
        DOMSource source = new DOMSource(this.asDOMResult.getNode());
        Transformer identity = TransformerFactory.newInstance().newTransformer();
        StringWriter stringOut = new StringWriter();
        Result result = new StreamResult(stringOut);
        identity.transform(source, result);

        return stringOut.toString();
    } catch (Throwable t) {
        SQLException sqlEx = SQLError.createSQLException(t.getMessage(), SQLError.SQL_STATE_ILLEGAL_ARGUMENT, this.exceptionInterceptor);
        sqlEx.initCause(t);

        throw sqlEx;
    }
}
项目:Cognizant-Intelligent-Test-Scripter    文件:SoapZephyrUtil.java   
public static String parseSOAPResponse(SOAPMessage soapResponse, String expression) {
    String retStr = null;
    try {
        final StringWriter writer = new StringWriter();
        TransformerFactory.newInstance().newTransformer().transform(new DOMSource(soapResponse.getSOAPPart()),
                new StreamResult(writer));
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        ByteArrayInputStream stream = new ByteArrayInputStream(writer.toString().getBytes("UTF-8"));
        Document doc = builder.parse(stream);
        XPath xPath = XPathFactory.newInstance().newXPath();
        //String expression = "//return";
        NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(doc, XPathConstants.NODESET);
        for (int index = 0; index < nodeList.getLength(); index++) {
            org.w3c.dom.Node node = nodeList.item(index);
            retStr = node.getTextContent();
        }
    } catch (TransformerConfigurationException ex) {
        Logger.getLogger(SoapZephyrUtil.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception e) {
        Logger.getLogger(SoapZephyrUtil.class.getName()).log(Level.SEVERE, null, e);
    }
    return retStr;
}
项目:massim    文件:Conversions.java   
/**
 * Transforms a DOM document to string.
 * @param doc the document to transform
 * @return the string representation of the doc or an empty string if sth. went wrong
 */
public static String docToString(Document doc, boolean indent){
    try {
        StringWriter writer = new StringWriter();
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        if (indent) {
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        }
        transformer.transform(new DOMSource(doc), new StreamResult(writer));
        return writer.getBuffer().toString();
    } catch (TransformerException e) {
        e.printStackTrace();
    }
    return "";
}
项目:the-vigilantes    文件:JDBC4MysqlSQLXML.java   
protected String domSourceToString() throws SQLException {
    try {
        DOMSource source = new DOMSource(this.asDOMResult.getNode());
        Transformer identity = TransformerFactory.newInstance().newTransformer();
        StringWriter stringOut = new StringWriter();
        Result result = new StreamResult(stringOut);
        identity.transform(source, result);

        return stringOut.toString();
    } catch (Throwable t) {
        SQLException sqlEx = SQLError.createSQLException(t.getMessage(), SQLError.SQL_STATE_ILLEGAL_ARGUMENT, this.exceptionInterceptor);
        sqlEx.initCause(t);

        throw sqlEx;
    }
}
项目:bohemia    文件:XmlUtils.java   
/** 
 * Converts the Node/Document/Element instance to XML payload. 
 * 
 * @param node the node/document/element instance to convert 
 * @return the XML payload representing the node/document/element 
 * @throws XmlException problem converting XML to string 
 */  
public static String nodeToString(Node node) throws XmlException {  
    String payload = null;  

    try {  
        Transformer tf = TransformerFactory.newInstance().newTransformer();  

        Properties props = tf.getOutputProperties();  
        props.setProperty(OutputKeys.INDENT, LOGIC_YES);  
        props.setProperty(OutputKeys.ENCODING, DEFAULT_ENCODE);  
        tf.setOutputProperties(props);  

        StringWriter writer = new StringWriter();  
        tf.transform(new DOMSource(node), new StreamResult(writer));  
        payload = writer.toString();  
        payload = payload.replaceAll(REG_INVALID_CHARS, " ");  
    } catch (TransformerException e) {  
        throw new XmlException(XmlException.XML_TRANSFORM_ERROR, e);  
    }  

    return payload;  
}
项目:alvisnlp    文件:AbstractAlvisNLP.java   
/**
 * CLI option: print the documentation for the specified module.
 * @param name
 * @throws TransformerException
 * @throws XPathExpressionException
 * @throws UnsupportedServiceException
 * @throws ServiceInstanciationException
 * @throws AmbiguousAliasException
 */
@CLIOption(value="-moduleDoc", stop=true)
public final void moduleDoc(String name) throws TransformerException, XPathExpressionException, UnsupportedServiceException, AmbiguousAliasException { 
    Document doc = getModuleDocumentation(name);
    // same ClassLoader as this class
    Source xslt = new StreamSource(getClass().getResourceAsStream(noColors ? "alvisnlp-doc2txt.xslt" : "alvisnlp-doc2ansi.xslt"));
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer(xslt);
    transformer.setParameter("name", bundle.getString(DocResourceConstants.MODULE_NAME).toUpperCase(locale));
    transformer.setParameter("synopsis", bundle.getString(DocResourceConstants.SYNOPSIS).toUpperCase(locale));
    transformer.setParameter("description", bundle.getString(DocResourceConstants.MODULE_DESCRIPTION).toUpperCase(locale));
    transformer.setParameter("parameters", bundle.getString(DocResourceConstants.MODULE_PARAMETERS).toUpperCase(locale));
    Source source = new DOMSource(doc);
    Result result = new StreamResult(System.out);
    transformer.transform(source, result);
}
项目:openjdk-jdk10    文件:TransformerTest02.java   
/**
 * Unit test for transform(StreamSource, StreamResult).
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testcase01() throws Exception {
    String outputFile = USER_DIR + "transformer02.out";
    String goldFile = GOLDEN_DIR + "transformer02GF.out";
    String xsltFile = XML_DIR + "cities.xsl";
    String xmlFile = XML_DIR + "cities.xml";

    try (FileInputStream fis = new FileInputStream(xmlFile);
            FileOutputStream fos = new FileOutputStream(outputFile)) {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DOMSource domSource = new DOMSource(dbf.newDocumentBuilder().
                parse(new File(xsltFile)));

        Transformer transformer = TransformerFactory.newInstance().
                newTransformer(domSource);
        StreamSource streamSource = new StreamSource(fis);
        StreamResult streamResult = new StreamResult(fos);

        transformer.setOutputProperty("indent", "no");
        transformer.transform(streamSource, streamResult);
    }
    assertTrue(compareWithGold(goldFile, outputFile));
}
项目:alvisnlp    文件:XMLWriter.java   
@Override
    public void process(ProcessingContext<Corpus> ctx, Corpus corpus) throws ModuleException {
        try {
            Logger logger = getLogger(ctx);
            EVALUATION_CONTEXT = new EvaluationContext(logger);
            Transformer transformer = getTransformer(ctx);

            XMLWriterResolvedObjects resObj = getResolvedObjects();
            EvaluationContext evalCtx = new EvaluationContext(logger);

            outDir.mkdirs();
            for (Element root : Iterators.loop(getRoots(evalCtx, corpus))) {
                transformer.reset();

                Document doc = XMLUtils.docBuilder.newDocument();
                doc.setUserData(ELEMENT_USER_DATA, root, null);
//              org.w3c.dom.Element elt = getElementProxy(doc, root);
//              doc.appendChild(elt);
                Source source = new DOMSource(doc);

                String fileNameString = resObj.fileName.evaluateString(evalCtx, root);
                File outFile = new File(outDir, fileNameString);
                Result result = new StreamResult(outFile);

                doTransform(ctx, transformer, source, result);
            }
        }
        catch (DOMException|TransformerException|IOException e) {
            rethrow(e);
        }
    }
项目:jetfuel    文件:StringAdapter.java   
/**
 * Converts an xml node to a string.
 * 
 * @param node
 * @return
 */
public String convertXml(Node node) {
    try {
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(node);
        StringWriter sw = new StringWriter();
        StreamResult result = new StreamResult(sw);
        transformer.transform(source, result);
        return sw.toString();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
项目:OperatieBRP    文件:BijhoudingWebService.java   
private BijhoudingVerzoekBericht parse(final DOMSource bericht) {
    final BijhoudingVerzoekBerichtParser parser = new BijhoudingVerzoekBerichtParser();
    try {
        final BijhoudingVerzoekBericht verzoekBericht = parser.parse(bericht);
        verzoekBericht.setXml(transformeerNaarXml(bericht));
        return verzoekBericht;
    } catch (ParseException e) {
        LOGGER.error("BijhoudingWebService fout bij het parsen van binnenkomend bericht: ", e);
        throw new WebServiceException(e);
    }
}