views:

145

answers:

2

I have a 300 KB xml file with 70 elements in it. I need to be efficient upon removing one of the root's elements. What is the best approach?

  • Should I detach the element in memory, save it and overwrite it by moving it?
  • Is there a better option?

I like org.jdom but any improvement is welcome

+1  A: 

Since there is no way to work with a XML file without loading and parsing it your first approach can work.. in addition you can't simply remove a piece from a file without rewriting it without the involved piece.

If what you want to exclude is quite simple and easily searchable you can also process the file and write it out while you read it without rewriting what you want to exclude.. that could be quite simpler than parsing it..

Jack
+1  A: 

What about a simple XSLT that copies all of the XML forward except for the specific elements that you don't want?

You can use a modified identity transform and just add empty templates for the elements that you want to suppress.

For example:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

    <xsl:template match="/">
        <xsl:apply-templates/>
    </xsl:template>

    <!--Identity transform copies all nodes and attributes by default -->
    <xsl:template match="@* | node()">
        <xsl:copy>
            <xsl:apply-templates />
        </xsl:copy>
    </xsl:template>

    <!--Create an empty template for the elements that you want to suppress-->
    <xsl:template match="ElementToRemove" />

</xsl:stylesheet>
Mads Hansen