Skip to content

Instantly share code, notes, and snippets.

@RicardoGeek
Last active October 21, 2020 08:37
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 RicardoGeek/f299fea401e6b170cf69dc2aedba483f to your computer and use it in GitHub Desktop.
Save RicardoGeek/f299fea401e6b170cf69dc2aedba483f to your computer and use it in GitHub Desktop.
XmlUtils
package com.ricardogeek.soap.security;
import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.StringReader;
import java.io.Writer;
public final class XmlUtils {
private static DocumentBuilder documentBuilder;
public static Document parseXml(String xmlString) throws IOException {
return parse(new InputSource(new StringReader(xmlString)));
}
static synchronized public Document parse(InputSource inputSource) throws IOException {
try {
return ensureDocumentBuilder().parse(inputSource);
} catch (SAXException e) {
throw new IOException(e.toString());
}
}
private static DocumentBuilder ensureDocumentBuilder() {
if (documentBuilder == null) {
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
documentBuilder = dbf.newDocumentBuilder();
} catch (ParserConfigurationException e) {
System.out.println("Error creating DocumentBuilder; " + e.getMessage());
}
}
return documentBuilder;
}
public static void serialize(Element elm, Writer writer) throws IOException {
try {
XmlObject xmlObject = XmlObject.Factory.parse(elm);
xmlObject.save(writer);
} catch (XmlException e) {
throw new IOException(e.toString());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment