2016-08-12 62 views
4

我使用转换GPathResultStringGPathResult为String没有XML声明

def gPathResult = new XmlSlurper().parseText('<node/>') 
XmlUtil.serialize(gPathResult) 

它工作正常,但我发现在我的XML面前XML声明

<?xml version="1.0" encoding="UTF-8"?><node/> 

我怎样才能在开始时将GPathResult转换为String而不是<?xml version="1.0" encoding="UTF-8"?>

回答

1

这是XmlUtil类中的代码。你会注意到它预先声明了xml声明,因此只需将其复制并移除即可:

private static String asString(GPathResult node) { 
    try { 
     Object builder = Class.forName("groovy.xml.StreamingMarkupBuilder").newInstance(); 
     InvokerHelper.setProperty(builder, "encoding", "UTF-8"); 
     Writable w = (Writable) InvokerHelper.invokeMethod(builder, "bindNode", node); 
     return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + w.toString(); 
    } catch (Exception e) { 
     return "Couldn't convert node to string because: " + e.getMessage(); 
    } 

}