问题
I have some test code snippet:
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()
And I run it online in here,above code will encouter some exception,error message as follow showing
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)
- Q:What I'm need?
- A:I want add an attribute which contains namespace for xml element.As my example ,I want and an attribute 'android:xxx' for element 'application',XmlUtil.serialize() will encounter error after adding that.Please help me. Any responsibility will be appreciated.
回答1:
Finally I address this issue by XmlParser
instead of 'XmlSlurper'.The following is right way.
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()
来源:https://stackoverflow.com/questions/60629223/how-to-add-an-attribute-which-contains-colonfor-xml-element-and-then-serializ