title: Extract a block of XML into another XML file in java
body: <p>I have a XML file called word.xml containing </p>
  
  <pre><code>&lt;A&gt; 
  &lt;Answer&gt;How was you day&lt;/Answer&gt; 
  &lt;Question&gt;Happy day &lt;/Question&gt;
  &lt;Biased&gt; good morning &lt;/Biased&gt;
  &lt;abc&gt;..............&lt;/abc&gt;
  .
  . // few more tags here
  .
  &lt;/A&gt;
  </code></pre>
  
  <p>Now i want to extract another XML file called word1.xml containing part of word1.xml</p>
  
  <pre><code>&lt;A&gt; 
  &lt;Answer&gt;How was you day&lt;/Answer&gt; 
  &lt;Question&gt;Happy day &lt;/Question&gt;
  &lt;/A&gt;
  </code></pre>
  
  <p>Java Code which I tried so far</p>
  
  <pre><code>import java.io.BufferedWriter;
  import java.io.File;
  import java.io.FileOutputStream;
  import java.io.FileWriter;
  import java.io.IOException;
  import java.io.OutputStreamWriter;
  import java.io.Writer;
  
  import javax.xml.parsers.DocumentBuilder;
  import javax.xml.parsers.DocumentBuilderFactory;
  import org.w3c.dom.Document;
  import org.w3c.dom.Element;
  import org.w3c.dom.Node;
  import org.w3c.dom.NodeList;
  
  public class ReadXMLFile {
  
  public static void main(String args[]) {
  try {
  
  File stocks = new File("word.xml");
  DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
  DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
  Document doc = dBuilder.parse(stocks);
  doc.getDocumentElement().normalize();
  
  System.out.println("root of xml file" + doc.getDocumentElement().getNodeName());
  NodeList nodes = doc.getElementsByTagName("A");
  System.out.println("==========================");
  
  for (int i = 0; i &lt; nodes.getLength(); i++) {
  Node node = nodes.item(i);
  System.out.println("i value---"+i);
  System.out.println(nodes.getLength());
  if (node.getNodeType() == Node.ELEMENT_NODE) {
  Element element = (Element) node;
  System.out.println(element.getTextContent());
  //element.getElementsByTagName(name)
  File statText = new File(i+".txt");
  FileOutputStream is = new FileOutputStream(statText);
  OutputStreamWriter osw = new OutputStreamWriter(is);    
  Writer w = new BufferedWriter(osw);
  w.write("&lt;Answer&gt;");
  w.write(element.getElementsByTagName("Answer").item(0).getTextContent());
  w.write("&lt;/Answer&gt;");
  w.write("Question");
  w.write(element.getElementsByTagName("Question").item(0).getTextContent());
  w.write("&lt;/Question&gt;");
  w.close();
  }
  }
  }
  catch (Exception ex) {
  ex.printStackTrace();
  }
  
  private static String getValue(String tag, Element element) {
  NodeList nodes = element.getElementsByTagName(tag).item(0).getChildNodes();
  Node node = (Node) nodes.item(0);
  return node.getNodeValue();
  }
  }
  }
  </code></pre>
  
  <p>I just want to include tags in my results. This is the DIRTY way of doing. Can you please suggest me the best way.Need help. Thanks in advance. </p>