Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You're right, with the standard XML API, there's not a good way - here's one example (may be bug ridden; it runs, but I wrote it a long time ago).</p> <pre><code>import javax.xml.*; import javax.xml.parsers.*; import javax.xml.transform.*; import javax.xml.transform.dom.*; import javax.xml.transform.stream.*; import org.w3c.dom.*; import java.io.*; public class Proc { public static void main(String[] args) throws Exception { //Parse the input document DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(new File("in.xml")); //Set up the transformer to write the output string TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); transformer.setOutputProperty("indent", "yes"); StringWriter sw = new StringWriter(); StreamResult result = new StreamResult(sw); //Find the first child node - this could be done with xpath as well NodeList nl = doc.getDocumentElement().getChildNodes(); DOMSource source = null; for(int x = 0;x &lt; nl.getLength();x++) { Node e = nl.item(x); if(e instanceof Element) { source = new DOMSource(e); break; } } //Do the transformation and output transformer.transform(source, result); System.out.println(sw.toString()); } } </code></pre> <p>It would seem like you could get the first child just by using doc.getDocumentElement().getFirstChild(), but the problem with that is if there is any whitespace between the root and the child element, that will create a Text node in the tree, and you'll get that node instead of the actual element node. The output from this program is:</p> <pre><code>D:\home\tmp\xml&gt;java Proc &lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;element1&gt; &lt;child attr1="blah"&gt; &lt;child2&gt;blahblah&lt;/child2&gt; &lt;/child&gt; &lt;/element1&gt; </code></pre> <p>I think you can suppress the xml version string if you don't need it, but I'm not sure on that. I would probably try to use a third party XML library if at all possible.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload