title: How do I remove elements and their children from Xml using Java and Stax
body: <p>I have a large file containing data like this</p>
  
  <pre><code>&lt;releases&gt;
     &lt;release&gt;
     ......
        &lt;companies&gt;
           &lt;company&gt;
           &lt;/company&gt;
        &lt;/companies&gt;
     &lt;/release&gt;
     &lt;release&gt;
     ......
  &lt;/releases&gt;
  </code></pre>
  
  <p>I want to produce and output file the same as the input file but with all the companies elements and their children removed.I'm trying to use Stax, I thought that it iterated down through the elements and then if I got a match I could just not write that element and the section would be removed. i.e if I throw away  element that causes  elements within it and  to be removed but it seems that it just removes the  element itself and nothing else, is that right ?</p>
  
  <p>i.e</p>
  
  <pre><code>&lt;releases&gt;
     &lt;release&gt;
     ......
     &lt;/release&gt;
     &lt;release&gt;
     ......
  &lt;/releases&gt;
  </code></pre>
  
  <p>This is the code I currently have:</p>
  
  <pre><code>        XMLInputFactory  inputFactory = XMLInputFactory.newInstance();
          XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
          InputStream in = new FileInputStream(source);
          XMLEventReader reader = inputFactory.createXMLEventReader(in);
  
          OutputStream out = new FileOutputStream(target);
          XMLEventWriter writer =  outputFactory.createXMLEventWriter(out);
          XMLEvent event;
          while(reader.hasNext()){
              event = reader.nextEvent();
              writer.add(event);
              if(event.getEventType() == XMLStreamConstants.START_ELEMENT)
              {
                  if(event.asStartElement().getName().toString().equalsIgnoreCase("companies"))
                  {
                      System.out.println("Deleting:"+event);
                      continue;
                  }
                  else
                  {
                      writer.add(event);
                  }
              }
              else
              {
                  writer.add(event);
              } 
          }
  </code></pre>