0

我有以下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。请帮忙

4

1 回答 1

0

要访问限定名称(带有命名空间的名称),您必须使用访问器:

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)
于 2020-06-20T19:52:32.553 回答