我有以下xml:
<profile:monitoringProfile xmlns:profile="http://xyz">
<profile:eventSource profile:eventSourceAddress="IN.terminal.out" profile:enabled="true">
<profile:eventPointDataQuery>
</profile:eventSource>
<profile:eventSource profile:eventSourceAddress="OUT.terminal.in" profile:enabled="true">
<profile:eventPointDataQuery>
</profile:eventSource>
</profile:monitoringProfile>
我想更新此 xml 中的属性值 想要从
<profile:eventSource profile:eventSourceAddress="IN.terminal.out" profile:enabled="**true**">
自
<profile:eventSource profile:eventSourceAddress="IN.terminal.out" profile:enabled="**false**">
用 groovy 编写了以下代码:
def monitorPropsKey=[IN.terminal.out, OUT.terminal.in]
def monitorPropsValue=[false, false]
File monitorxml = new File("test.xml")
def prof = new groovy.xml.Namespace("http://xyz",'profile')
def monitorParseXml = new XmlParser().parse(monitorxml)
def arrayLength = monitorPropsKey.size() - 1
for (int i=0; i<=arrayLength; i++) {
monitorParseXml.prof.eventSource[i].each {
if(it.prof.@eventSourceAddress.text() == "${monitorPropsKey[i]}") {
it.prof.@enabled = "${monitorPropsValue[i]}"
}
}
}
它仍然给出原始的XML,它不更新XML。请帮忙
要访问限定名称(带有命名空间的名称(,您必须使用访问器:
xml[NAMESPACE.NAME]
访问 xml 元素
和访问属性xml.attributes()[NAMESPACE.NAME]
def xmlstr = '''
<profile:monitoringProfile xmlns:profile="http://xyz">
<profile:eventSource profile:eventSourceAddress="IN.terminal.out" profile:enabled="true">
<profile:eventPointDataQuery/>
</profile:eventSource>
<profile:eventSource profile:eventSourceAddress="OUT.terminal.in" profile:enabled="true">
<profile:eventPointDataQuery/>
</profile:eventSource>
</profile:monitoringProfile>
'''
def monitorPropsKey=['IN.terminal.out', 'OUT.terminal.in']
def monitorPropsValue=[false, false]
def prof = new groovy.xml.Namespace("http://xyz")
def monitorParseXml = new XmlParser().parseText(xmlstr)
for (int i=0; i<monitorPropsKey.size(); i++) {
def e = monitorParseXml[prof.eventSource].find{ it.attributes()[prof.eventSourceAddress]==monitorPropsKey[i] }
if(e)e.attributes()[prof.enabled]=monitorPropsValue[i]
else println "key '${monitorPropsKey[i]}' not found"
}
println groovy.xml.XmlUtil.serialize(monitorParseXml)