Skip to content

Instantly share code, notes, and snippets.

@Crydust
Created April 24, 2017 16:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Crydust/fcf3cf6c88b534d69fac104c94f97b39 to your computer and use it in GitHub Desktop.
Save Crydust/fcf3cf6c88b534d69fac104c94f97b39 to your computer and use it in GitHub Desktop.
create xml in java
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