我有一些测试代码片段:
import groovy.xml.XmlUtil
class Greet {
Greet() { }
def salute() {
println "Hello !"
def input = """
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application >
<activity android:name="me.aolphn.MainActivity">
</activity>
</application>
</manifest>
"""
// def root = new XmlParser(false, true).parseText(input)
def root = new XmlSlurper(false, true).parseText(input)
root.'application'.@'android:txt'='this is txt'
XmlUtil.serialize(root)
}
}
g = new Greet() // create object
g.salute()
并且我在here中在线运行,以上代码将引发一些异常,错误消息如下所示:>
groovy.lang.GroovyRuntimeException: org.xml.sax.SAXParseException; lineNumber: 2; columnNumber: 24; Element type "application" must be followed by either attribute specifications, ">" or "/>".
at Greet.salute(Script1.groovy:24)
at Greet$salute.call(Unknown Source)
at Script1.run(Script1.groovy:29)
我有一些测试代码片段:import groovy.xml.XmlUtil类Greet {Greet(){} def salute(){println“你好!” def input =“”“
最后,我用XmlParser
而不是'XmlSlurper'解决了这个问题。以下是正确的方法。
import groovy.xml.XmlUtil
import groovy.xml.StreamingMarkupBuilder
class Greet {
def name
Greet(who) { name = who[0].toUpperCase() +
who[1..-1] }
def salute() {
println "Hello !"
def input = """
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application xmlns:android="http://schemas.android.com/apk/res/android"
android:txt="this is origin">
<activity android:name="com.cloud.chsocialtest.MainActivity">
</activity>
</application>
</manifest>
"""
def root = new XmlParser(false, true).parseText(input)
//def root = new XmlSlurper(false, true).parseText(input).declareNamespace(android:"http://schemas.android.com/apk/res/android")
//def writer = new StringWriter()
//root.'application'.attributes().put('@android:txt1','t1')
root.'application'[0].attributes()['android:new']='txt aa'
println("========:\n"+
XmlUtil.serialize(root))
//print writer.toString()
}
}
g = new Greet('world') // create object
g.salute()