开发者

Remove an element from an xml File using jdom

I have a 300 KB xml file wi开发者_JAVA技巧th 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


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜