下面列出了怎么用javax.xml.transform.dom.DOMSource的API类实例代码及写法,或者点击链接到github查看源代码。
public void serialize(Element el) throws IOException {
if (output == null)
throw new IllegalStateException("OutputStream cannot be null");
try {
DOMSource source = new DOMSource(el);
XMLInputFactory readerFactory = XMLInputFactory.newInstance();
XMLStreamReader streamReader = readerFactory
.createXMLStreamReader(source);
XMLEventReader eventReader = readerFactory
.createXMLEventReader(streamReader);
XMLEventWriter eventWriter = writerFactory
.createXMLEventWriter(output);
eventWriter.add(eventReader);
eventWriter.close();
} catch (XMLStreamException ex) {
IOException ioex = new IOException("Cannot serialize: " + el);
ioex.initCause(ex);
throw ioex;
}
}
/**
* Writes the XML document to an output stream
*
* @param svgDocument
* @param outputStream
* @throws Exception
*/
private void writeDocumentToOutputStream( Document svgDocument,
OutputStream outputStream ) throws Exception
{
if ( svgDocument != null && outputStream != null )
{
OutputStreamWriter writer = null;
writer = SecurityUtil.newOutputStreamWriter( outputStream, "UTF-8" ); //$NON-NLS-1$
DOMSource source = new DOMSource( svgDocument );
StreamResult result = new StreamResult( writer );
// need to check if we should use sun's implementation of the
// transform factory. This is needed to work with jdk1.4 and jdk1.5
// with tomcat
checkForTransformFactoryImpl( );
TransformerFactory transFactory = SecurityUtil.newTransformerFactory( );
Transformer transformer = transFactory.newTransformer( );
transformer.transform( source, result );
}
}
/**
* A method to create a SOAP message and retrieve it as byte.
*
* @param version
* the SOAP version to be used (1.1 or 1.2).
* @param headerBlocks
* the list of Header Blocks to be included in the SOAP Header .
* @param body
* the XML message to be included in the SOAP BODY element.
* @param encoding
* the encoding to be used for the message creation.
*
* @return The created SOAP message as byte.
*
* @author Simone Gianfranceschi
*/
public static byte[] getSoapMessageAsByte(String version,
List headerBlocks, Element body, String encoding) throws Exception {
Document message = createSoapMessage(version, headerBlocks, body);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
TransformerFactory tf = TransformerFactory.newInstance();
// Fortify Mod: prevent external entity injection
tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
Transformer t = tf.newTransformer();
// End Fortify Mod
t.setOutputProperty(OutputKeys.ENCODING, encoding);
t.transform(new DOMSource(message), new StreamResult(baos));
// System.out.println("SOAP MESSAGE : " + baos.toString());
return baos.toByteArray();
}
public Object unmarshal( Source source ) throws JAXBException {
if( source == null ) {
throw new IllegalArgumentException(
Messages.format( Messages.MUST_NOT_BE_NULL, "source" ) );
}
if(source instanceof SAXSource)
return unmarshal( (SAXSource)source );
if(source instanceof StreamSource)
return unmarshal( streamSourceToInputSource((StreamSource)source));
if(source instanceof DOMSource)
return unmarshal( ((DOMSource)source).getNode() );
// we don't handle other types of Source
throw new IllegalArgumentException();
}
private Source[] getSchemaSources() throws Exception {
List<Source> list = new ArrayList<Source>();
String file = getClass().getResource("hello_literal.wsdl").getFile();
Source source = new StreamSource(new FileInputStream(file), file);
Transformer trans = TransformerFactory.newInstance().newTransformer();
DOMResult result = new DOMResult();
trans.transform(source, result);
// Look for <xsd:schema> element in wsdl
Element e = ((Document) result.getNode()).getDocumentElement();
NodeList typesList = e.getElementsByTagNameNS("http://schemas.xmlsoap.org/wsdl/", "types");
NodeList schemaList = ((Element) typesList.item(0)).getElementsByTagNameNS("http://www.w3.org/2001/XMLSchema", "schema");
Element elem = (Element) schemaList.item(0);
list.add(new DOMSource(elem, file + "#schema0"));
// trans.transform(new DOMSource(elem), new StreamResult(System.out));
return list.toArray(new Source[list.size()]);
}
@Override
public void serialize(final Document flowConfiguration, final OutputStream os) throws FlowSerializationException {
try {
final DOMSource domSource = new DOMSource(flowConfiguration);
final StreamResult streamResult = new StreamResult(new BufferedOutputStream(os));
// configure the transformer and convert the DOM
final TransformerFactory transformFactory = TransformerFactory.newInstance();
final Transformer transformer = transformFactory.newTransformer();
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
// transform the document to byte stream
transformer.transform(domSource, streamResult);
} catch (final DOMException | TransformerFactoryConfigurationError | IllegalArgumentException | TransformerException e) {
throw new FlowSerializationException(e);
}
}
@Test
public void testCreateCrossrefXml_SkippedVolume() throws Exception {
File targetFolder = temp.getRoot();
CrossrefBuilder builder = new CrossrefBuilder(targetFolder);
builder.addPeriodicalTitle("1210-8510", "titleTest", "abbrevTest", "print");
builder.addIssue("10", "2010", "uuid");
Document article = builder.getDocumentBuilder().parse(
CejshBuilderTest.class.getResource("article_mods.xml").toExternalForm());
builder.addArticle(article);
Document articles = builder.mergeArticles();
StringWriter dump = new StringWriter();
TransformErrorListener errors = builder.createCrossrefXml(new DOMSource(articles), new StreamResult(dump));
// System.out.println(dump);
assertTrue(errors.getErrors().toString(), errors.getErrors().isEmpty());
List<String> validateErrors = builder.validateCrossref(new StreamSource(new StringReader(dump.toString())));
assertTrue(validateErrors.toString(), validateErrors.isEmpty());
}
public XMLSignatureInput engineResolveURI(ResourceResolverContext context) throws ResourceResolverException {
String id = context.attr.getNodeValue();
if (id.startsWith("#")) {
id = id.substring(1);
}
if (LOG.isDebugEnabled()) {
try {
LOG.debug("Selected document: " + ConnectorXmlUtils.flatten(ConnectorXmlUtils.toString((Source)(new DOMSource(this.doc)))));
} catch (TechnicalConnectorException var5) {
LOG.error(var5.getMessage());
}
}
Node selectedElem = this.doc.getElementById(id);
if (LOG.isDebugEnabled()) {
LOG.debug("Try to catch an Element with ID " + id + " and Element was " + selectedElem);
}
this.processElement(context.attr, context.baseUri, selectedElem, id);
XMLSignatureInput result = new XMLSignatureInput(selectedElem);
result.setExcludeComments(true);
result.setMIMEType("text/xml");
result.setSourceURI(context.baseUri != null ? context.baseUri.concat(context.attr.getNodeValue()) : context.attr.getNodeValue());
return result;
}
private void parseSchemaElement( Element element )
throws IOException {
try {
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty( "indent", "yes" );
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult( sw );
DOMSource source = new DOMSource( element );
transformer.transform( source, result );
InputSource schemaSource = new InputSource( new StringReader( sw.toString() ) );
schemaSource.setSystemId( definition.getDocumentBaseURI() );
schemaParser.parse( schemaSource );
} catch( SAXException | TransformerException e ) {
throw new IOException( e );
}
}
@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},
};
}
private static final void writeDoc(Document doc, OutputStream out)
throws IOException
{
try {
TransformerFactory tf = TransformerFactory.newInstance();
try {
tf.setAttribute("indent-number", new Integer(2));
} catch (IllegalArgumentException iae) {
}
Transformer t = tf.newTransformer();
t.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, doc.getDoctype().getSystemId());
t.setOutputProperty(OutputKeys.INDENT, "yes");
t.transform(new DOMSource(doc),
new StreamResult(new BufferedWriter(new OutputStreamWriter(out, "UTF-8"))));
} catch(TransformerException e) {
throw new AssertionError(e);
}
}
@Test
public void testServiceGetPortUsingEndpointReference() throws Exception {
BusFactory.setDefaultBus(getBus());
GreeterImpl greeter1 = new GreeterImpl();
try (EndpointImpl endpoint = new EndpointImpl(getBus(), greeter1, (String)null)) {
endpoint.publish("http://localhost:8080/test");
javax.xml.ws.Service s = javax.xml.ws.Service
.create(new QName("http://apache.org/hello_world_soap_http", "SoapPort"));
InputStream is = getClass().getResourceAsStream("resources/hello_world_soap_http_infoset.xml");
Document doc = StaxUtils.read(is);
DOMSource erXML = new DOMSource(doc);
EndpointReference endpointReference = EndpointReference.readFrom(erXML);
WebServiceFeature[] wfs = new WebServiceFeature[] {};
Greeter greeter = s.getPort(endpointReference, Greeter.class, wfs);
String response = greeter.greetMe("John");
assertEquals("Hello John", response);
}
}
/**
* Write out the non-default properties in this configuration to the given
* {@link Writer}.
*
* @param out the writer to write to.
*/
public void writeXml(Writer out) throws IOException {
Document doc = asXmlDocument();
try {
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(out);
TransformerFactory transFactory = TransformerFactory.newInstance();
Transformer transformer = transFactory.newTransformer();
// Important to not hold Configuration log while writing result, since
// 'out' may be an HDFS stream which needs to lock this configuration
// from another thread.
transformer.transform(source, result);
} catch (TransformerException te) {
throw new IOException(te);
}
}
public Object unmarshal0( Source source, JaxBeanInfo expectedType ) throws JAXBException {
if (source instanceof SAXSource) {
SAXSource ss = (SAXSource) source;
XMLReader locReader = ss.getXMLReader();
if (locReader == null) {
locReader = getXMLReader();
}
return unmarshal0(locReader, ss.getInputSource(), expectedType);
}
if (source instanceof StreamSource) {
return unmarshal0(getXMLReader(), streamSourceToInputSource((StreamSource) source), expectedType);
}
if (source instanceof DOMSource) {
return unmarshal0(((DOMSource) source).getNode(), expectedType);
}
// we don't handle other types of Source
throw new IllegalArgumentException();
}
private static void addMountPointChild(final MountPointData mount, final URI namespace, final String localName,
final DOMSource source) {
final DOMSourceMountPointChild child = new DOMSourceMountPointChild(source);
if (YangLibraryConstants.MODULE_NAMESPACE.equals(namespace)) {
final Optional<ContainerName> optName = ContainerName.forLocalName(localName);
if (optName.isPresent()) {
mount.setContainer(optName.get(), child);
return;
}
LOG.warn("Encountered unknown element {} from YANG Library namespace", localName);
} else if (SchemaMountConstants.RFC8528_MODULE.getNamespace().equals(namespace)) {
mount.setSchemaMounts(child);
return;
}
mount.addChild(child);
}
/**
* Write the server.xml and bootstrap.properties to the server config
* directory
*
* @throws TransformerException
* @throws IOException
*/
public void writeToServer() throws TransformerException, IOException {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
// Replace auto-generated server.xml
DOMSource server = new DOMSource(serverXml);
StreamResult serverResult = new StreamResult(new File(serverPath + "/server.xml"));
transformer.transform(server, serverResult);
// Create configDropins/default path
Path configDropins = Paths.get(serverPath + CONFIG_DROPINS_DIR);
Files.createDirectories(configDropins);
// Write variables.xml to configDropins
DOMSource variables = new DOMSource(variablesXml);
StreamResult variablesResult = new StreamResult(new File(serverPath + CONFIG_DROPINS_DIR + "/variables.xml"));
transformer.transform(variables, variablesResult);
}
private String copyDOMToString(Document wadlDoc) throws Exception {
DOMSource domSource = new DOMSource(wadlDoc);
// temporary workaround
StringWriter stringWriter = new StringWriter();
TransformerFactory transformerFactory = TransformerFactory.newInstance();
transformerFactory.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true);
try {
transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "");
} catch (IllegalArgumentException ex) {
// ignore
}
Transformer transformer = transformerFactory.newTransformer();
transformer.transform(domSource, new StreamResult(stringWriter));
return stringWriter.toString();
}
/**
* XML Node to string
* @param node XML node
* @return XML node string representation
*/
public static String nodeToString(Node node)
{
StringWriter sw = new StringWriter();
try
{
Transformer t = TransformerFactory.newInstance().newTransformer();
t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
t.setOutputProperty(OutputKeys.INDENT, "no");
/* CB - Since everything is already stored as strings in memory why shoud an encoding be required here? */
t.setOutputProperty(OutputKeys.ENCODING, RuntimeConstants.ENCODING_DEFAULT);
t.transform(new DOMSource(node), new StreamResult(sw));
}
catch (TransformerException te)
{
LOGGER.error("could not convert XML node to string", te);
}
return sw.toString();
}
public static String asString(Node node, boolean formatted) {
try {
Transformer transformer = TransformerFactory.newInstance().newTransformer();
if (formatted) {
transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // NOI18N
}
if (!(node instanceof Document)) {
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); // NOI18N
}
StreamResult result = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(node);
transformer.transform(source, result);
return result.getWriter().toString();
} catch (TransformerException ex) {
LOGGER.log(Level.INFO, null, ex);
}
return null;
}
/**
* Unmarshals the given provided {@code javax.xml.transform.Source} into an object graph.
* <p>This implementation inspects the given result, and calls {@code unmarshalDomSource},
* {@code unmarshalSaxSource}, or {@code unmarshalStreamSource}.
* @param source the source to marshal from
* @return the object graph
* @throws IOException if an I/O Exception occurs
* @throws XmlMappingException if the given source cannot be mapped to an object
* @throws IllegalArgumentException if {@code source} is neither a {@code DOMSource},
* a {@code SAXSource}, nor a {@code StreamSource}
* @see #unmarshalDomSource(javax.xml.transform.dom.DOMSource)
* @see #unmarshalSaxSource(javax.xml.transform.sax.SAXSource)
* @see #unmarshalStreamSource(javax.xml.transform.stream.StreamSource)
*/
@Override
public final Object unmarshal(Source source) throws IOException, XmlMappingException {
if (source instanceof DOMSource) {
return unmarshalDomSource((DOMSource) source);
}
else if (StaxUtils.isStaxSource(source)) {
return unmarshalStaxSource(source);
}
else if (source instanceof SAXSource) {
return unmarshalSaxSource((SAXSource) source);
}
else if (source instanceof StreamSource) {
return unmarshalStreamSource((StreamSource) source);
}
else {
throw new IllegalArgumentException("Unknown Source type: " + source.getClass());
}
}
private static void saveDocument(Document doc, File file) {
try {
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.transform(new DOMSource(doc), new StreamResult(file));
} catch (TransformerException e) {
throw new RuntimeException(e);
}
}
private static Node tryExtractNodeFromDOMSource(Source s) {
if (s instanceof DOMSource) {
@SuppressWarnings("unchecked") DOMSource ds = (DOMSource) s;
return ds.getNode();
}
return null;
}
private String serialize2(String unformattedXml) throws Exception {
final Document document = XmlUtil.stringToXml(unformattedXml);
TransformerFactory tfactory = TransformerFactory.newInstance();
StringWriter buffer = new StringWriter();
Transformer serializer = tfactory.newTransformer();
// Setup indenting to "pretty print"
serializer.setOutputProperty(OutputKeys.INDENT, "yes");
serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
serializer.transform(new DOMSource(document), new StreamResult(buffer));
return buffer.toString();
}
public static DOMSource getSigStream(AxisService service, ByteArrayOutputStream wsdlOutStream, Map paramMap)
throws TransformerFactoryConfigurationError, TransformerException,
ParserConfigurationException {
Source wsdlSource = new StreamSource(new ByteArrayInputStream(wsdlOutStream.toByteArray()));
InputStream sigStream =
Util.class.getClassLoader().getResourceAsStream(WSDL2SIG_XSL_LOCATION);
Source wsdl2sigXSLTSource = new StreamSource(sigStream);
DocumentBuilder docB = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document docSig = docB.newDocument();
Result resultSig = new DOMResult(docSig);
Util.transform(wsdlSource, wsdl2sigXSLTSource, resultSig, paramMap, new SchemaURIResolver(service));
return new DOMSource(docSig);
}
private static void saveXMLFile(final Document document, final File xmlFile) throws IOException, TransformerException {
final TransformerFactory transformerFactory = TransformerFactory.newInstance();
transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
// Ant's build.xml can not use this
// transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
final Transformer transformer = transformerFactory.newTransformer();
try ( FileOutputStream out = new FileOutputStream(xmlFile)) {
final Source saveSource = new DOMSource(document);
final Result saveResult = new StreamResult(out);
transformer.transform(saveSource, saveResult);
}
}
public void serialize(Node node) {
try {
mTransformer.transform(new DOMSource(node), createSaxResultObject());
} catch (TransformerException e) {
throw new UIMARuntimeException(e);
}
}
private void setSubsystemXml(String value, String unit) throws IOException {
try {
String template = readResource("keycloak-saml-1.3.xml");
if (value != null) {
// assign the AllowedClockSkew element using DOM
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = db.parse(new InputSource(new StringReader(template)));
// create the skew element
Element allowedClockSkew = doc.createElement(Constants.XML.ALLOWED_CLOCK_SKEW);
if (unit != null) {
allowedClockSkew.setAttribute(Constants.XML.ALLOWED_CLOCK_SKEW_UNIT, unit);
}
allowedClockSkew.setTextContent(value);
// locate the IDP and insert the node
XPath xPath = XPathFactory.newInstance().newXPath();
NodeList nodeList = (NodeList) xPath.compile("/subsystem/secure-deployment[1]/SP/IDP").evaluate(doc, XPathConstants.NODESET);
nodeList.item(0).appendChild(allowedClockSkew);
// transform again to XML
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(doc), new StreamResult(writer));
subsystemXml = writer.getBuffer().toString();
} else {
subsystemXml = template;
}
} catch (DOMException | ParserConfigurationException | SAXException | TransformerException | XPathExpressionException e) {
throw new IOException(e);
}
}
static public Document cloneDocument(Document document) {
if (document == null) return null;
Document result = newDocument();
try {
identityTransformer.transform(new DOMSource( document), new DOMResult( result));
} catch (TransformerException e) {
e.printStackTrace();
}
return result;
}
public boolean handleOutbound(SOAPMessageContext context) {
this.endpoint = (String)context.get("javax.xml.ws.service.endpoint.address");
if (distributor.mustCache(this.endpoint)) {
try {
Node body = context.getMessage().getSOAPBody().cloneNode(true);
this.request = new DOMSource(ConnectorXmlUtils.getFirstChildElement(body));
} catch (SOAPException var3) {
LOG.trace("Unable to determine endpoint and payload", var3);
}
}
return true;
}
@Nonnull
public static String toString(@Nullable Node node) {
try {
StringWriter out = new StringWriter();
Transformer identityTransformer = TransformerFactory.newInstance().newTransformer();
identityTransformer.transform(new DOMSource(node), new StreamResult(out));
return out.toString();
} catch (TransformerException e) {
LOGGER.log(Level.WARNING, "Exception dumping node " + node, e);
return e.toString();
}
}