title: Java XML parsing - merging the output of xi:include
body: <p>I have an XML file that has the following:</p>
  
  <pre><code>&lt;contexts&gt;
      &lt;context name="a"&gt;
          &lt;xi:include xmlns:xi="http://www.w3.org/2003/XInclude" href="reuse.xml"/&gt;
          &lt;other_stuff/&gt;
      &lt;/context&gt;
      &lt;context name="b"&gt;
          &lt;xi:include xmlns:xi="http://www.w3.org/2003/XInclude" href="reuse.xml"/&gt;
          &lt;other_stuff/&gt;
      &lt;/context&gt;
  &lt;/contexts&gt;
  </code></pre>
  
  <p>... and the reuse.xml referenced by the XInclude above which contains something like this:</p>
  
  <pre><code>&lt;good_stuff/&gt;&lt;!-- and a bunch of complex stuff -&gt;
  </code></pre>
  
  <p>I'm trying to write some Java code which can generate some string output for each context element (easy) but instead of the xi:include line, replace that with the contents of the included file i.e. give me an 'exploded' String for each Context like this:</p>
  
  <pre><code>&lt;context name="a"&gt;
      &lt;good_stuff/&gt;&lt;!-- and a bunch of complex stuff -&gt;
      &lt;other_stuff/&gt;
  &lt;/context&gt;
  </code></pre>
  
  <p>Rather than what I'm getting now:</p>
  
  <pre><code>&lt;context name="a"&gt;
      &lt;xi:include xmlns:xi="http://www.w3.org/2003/XInclude" href="reuse.xml"/&gt; 
      &lt;other_stuff/&gt;
  &lt;/context&gt;
  </code></pre>
  
  <p>Hopefully I've explained myself clearly that I don't want the xi:include text in my output, but rather the contents of the other file it should be replaced by.</p>
  
  <p>I'm setting the parser to be XInclude and Namespace aware:</p>
  
  <pre><code>DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  factory.setNamespaceAware(true);
  factory.setXIncludeAware(true);
  </code></pre>
  
  <p>...</p>
  
  <p>Then getting the child nodes of the type I want (type is giving me the Context in this case).</p>
  
  <pre><code>NodeList result = doc.getElementsByTagName(type).item(0).getChildNodes();
  </code></pre>
  
  <p>But when I iterate over this, and pass each element to the StringWriter with the following, it isn't replacing the xi:include;</p>
  
  <pre><code>StringWriter sw = new StringWriter();
  Transformer serializer = TransformerFactory.newInstance().newTransformer();
  serializer.setOutputProperty(OutputKeys.INDENT, "no");
  serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
  serializer.setOutputProperty(OutputKeys.STANDALONE, "yes");
  serializer.transform(new DOMSource(element), new StreamResult(sw));
  String result = sw.toString();
  </code></pre>
  
  <p>Is there a way to do this with the JDK 7/8 built-in XML parsers, other than String manipulation to replace the xi:include myself?</p>
  
  <p>Thanks for any assistance!</p>