Skip to content

Instantly share code, notes, and snippets.

@imantung
Created July 7, 2020 22:52
Show Gist options
  • Save imantung/affe49fda15f4b5c2af9827e79ab9b06 to your computer and use it in GitHub Desktop.
Save imantung/affe49fda15f4b5c2af9827e79ab9b06 to your computer and use it in GitHub Desktop.
package coba;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.net.URL;
public class Main {
public static void main(String[] args) {
URL src = ClassLoader.getSystemClassLoader().getResource("./search.xml");
File initialFile = new File(src.getPath());
try {
InputStream in = new FileInputStream(initialFile);
Node body = getSoapBody(in);
Element req = getFirstElement(body);
System.out.println(nodeToString(req));
} catch (Exception e) {
e.printStackTrace();
}
}
public static Node getSoapBody(InputStream in) throws Exception {
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(in);
return getSoapBody(doc);
}
public static Node getSoapBody(Document doc) throws Exception {
Node root = doc.getFirstChild();
if (root == null) {
throw new Exception("XML Root is missing");
}
return getSoapBody(root);
}
public static Node getSoapBody(Node root) throws Exception {
NodeList childNodes = root.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
Node child = childNodes.item(i);
if (child.getNodeName().endsWith(":Body")) {
return child;
}
}
return null;
}
public static String nodeToString(Node node) throws Exception {
StringWriter sw = new StringWriter();
Transformer t = TransformerFactory.newInstance().newTransformer();
t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
t.setOutputProperty(OutputKeys.INDENT, "yes");
t.transform(new DOMSource(node), new StreamResult(sw));
return sw.toString().trim();
}
public static Element getFirstElement(Node parent){
NodeList childNodes = parent.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
Node child = childNodes.item(i);
if(child.getNodeType() == Node.ELEMENT_NODE){
return (Element) child;
}
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment