Created
April 24, 2017 16:11
-
-
Save Crydust/fcf3cf6c88b534d69fac104c94f97b39 to your computer and use it in GitHub Desktop.
create xml in java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
try { | |
final ByteArrayOutputStream bos = new ByteArrayOutputStream(); | |
final XMLStreamWriter writer = XMLOutputFactory.newInstance().createXMLStreamWriter(bos); | |
writer.writeStartDocument("UTF-8", "1.0"); | |
writer.writeStartElement("a"); | |
writer.writeDefaultNamespace(NS); | |
writer.writeStartElement("b"); | |
writer.writeStartElement("c"); | |
writer.writeCharacters("d"); | |
writer.writeEndElement(); | |
writer.writeStartElement("e"); | |
writer.writeStartElement("f"); | |
writer.writeCharacters("g"); | |
writer.writeEndElement(); | |
writer.writeEndElement(); | |
writer.writeEndElement(); | |
writer.writeEndElement(); | |
//System.out.println(new String(bos.toByteArray(), StandardCharsets.UTF_8)); | |
return new ByteArrayInputStream(bos.toByteArray()); | |
} catch (Exception e) { | |
throw new RuntimeException(e); | |
} | |
try { | |
final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); | |
final Node policyClause = doc | |
.appendChild(doc.createElementNS(NS, "a")) | |
.appendChild(doc.createElementNS(NS, "b")); | |
policyClause | |
.appendChild(doc.createElementNS(NS, "c")) | |
.setTextContent("d"); | |
policyClause | |
.appendChild(doc.createElementNS(NS, "e")) | |
.appendChild(doc.createElementNS(NS, "f")) | |
.setTextContent("g"); | |
final ByteArrayOutputStream bos = new ByteArrayOutputStream(); | |
TransformerFactory.newInstance().newTransformer().transform(new DOMSource(doc), new StreamResult(bos)); | |
//System.out.println(new String(bos.toByteArray(), StandardCharsets.UTF_8)); | |
return new ByteArrayInputStream(bos.toByteArray()); | |
} catch (Exception e) { | |
throw new RuntimeException(e); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment