如何为xml元素添加包含冒号(:)的属性,然后以Groovy对其进行序列化?

问题描述 投票:0回答:1

我有一些测试代码片段:


​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)
  • 问:我需要什么?
  • A:我想添加一个包含xml元素名称空间的属性。作为我的示例,我想要一个元素'application'的属性'android:xxx',XmlUtil.serialize()添加后会遇到错误。请帮助我。任何责任将不胜感激。

我有一些测试代码片段:import groovy.xml.XmlUtil类Greet {Greet(){} def salute(){println“你好!” def input =“”“

xml serialization groovy xml-parsing xmlserializer
1个回答
0
投票

最后,我用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()
​​​​​​​​​​​​​​​​​​​​​​​
© www.soinside.com 2019 - 2024. All rights reserved.