groovy-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From garneke <kenton.gar...@issinc.com>
Subject Re: XmlSlurper Namespace Question
Date Mon, 18 Apr 2016 17:18:55 GMT
Thanks!  - I have extended the example to show four variations of this.  
I my code I was creating a SAXParser pool to initialize the XmlSlurper with
because I was told it greatly reduce the time and overhead of instantiating
an XmlSlurper object from scratch.
Although, I thought I had tested with and without a SAXParser I must have
missed something.
So from the four examples here you can see that the SAXParser introduces the
namespaces that I did not want.

Perhaps I could just use a pool of XmlSlurper objects..

import groovy.xml.*;
import groovy.util.slurpersupport.GPathResult;
import javax.xml.parsers.*;


public boolean removePath(def xml, def path) throws Exception{
    Eval.x( xml, "x.${path}.replaceNode({})" )
    return true;
}

public GPathResult getPathFilter( GPathResult gpResult, String filterPath )
{
    removePath( gpResult, filterPath );
    return gpResult;
}
 
String xml = '''
<a:root xmlns:a="urn:a" xmlns:b="urn:b" xmlns:c="urn:c">
    <a:child1>child1</a:child1>
    <b:child2>
        <b:content>
            <b:dataNode>data</b:dataNode>
        </b:content>
    </b:child2>
    <c:child3>child3</c:child3>
</a:root>
'''
String nodeToRemove = 'child2.content.dataNode';
String nodeToRemove_Incl_NS = "'b:child2'.'b:content'.'b:dataNode'";
SAXParserFactory parserFactory = SAXParserFactory.newInstance();

// 1) - SAXParse NS Aware
parserFactory.setNamespaceAware( true );
SAXParser parser = parserFactory.newSAXParser();
def root_one = new XmlSlurper(parser).parseText(xml)
getPathFilter( root_one , nodeToRemove);
def newXml =  XmlUtil.serialize(root_one)
print "1) - SAXParse NS Aware Filter:["+nodeToRemove+"]\n" + newXml

// 2) - SAXParse NON-NS Aware
parserFactory.setNamespaceAware( false );
parser = parserFactory.newSAXParser();
def root_two = new XmlSlurper(parser).parseText(xml)
getPathFilter( root_two , nodeToRemove_Incl_NS);
newXml =  XmlUtil.serialize(root_two)
print "\n2) - SAXParse Non-NS Aware Filter:["+nodeToRemove_Incl_NS+"]\n" +
newXml

// 3) - Slurper NS Aware
def root_three = new XmlSlurper(false, true).parseText(xml)
getPathFilter( root_three , nodeToRemove);
newXml =  XmlUtil.serialize(root_three)
print "\n3) - XmlSlurper NS Aware Filter:["+nodeToRemove+"]\n" + newXml

// 4) - Slurper Non-NS Aware
def root_four = new XmlSlurper(false, false).parseText(xml)
getPathFilter( root_four , nodeToRemove_Incl_NS);
newXml =  XmlUtil.serialize(root_four)
print "\n4) - XmlSlurper Non-NS Aware Filter:["+nodeToRemove_Incl_NS+"]\n" +
newXml





--
View this message in context: http://groovy.329449.n5.nabble.com/XmlSlurper-Namespace-Question-tp5732293p5732402.html
Sent from the Groovy Users mailing list archive at Nabble.com.

Mime
View raw message