Llistes Sugra
Llistes Sugra

Reputation: 991

Remove an element from an xml File using jdom

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?

I like org.jdom but any improvement is welcome

Upvotes: 0

Views: 873

Answers (2)

Mads Hansen
Mads Hansen

Reputation: 66783

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>

Upvotes: 1

Jack
Jack

Reputation: 133609

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..

Upvotes: 1

Related Questions