Last active
October 21, 2020 08:37
-
-
Save RicardoGeek/f299fea401e6b170cf69dc2aedba483f to your computer and use it in GitHub Desktop.
XmlUtils
This file contains hidden or 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
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