синтаксический анализ xml с пространством имен в groovy - PullRequest
0 голосов
/ 20 июня 2020

У меня есть следующее 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. Пожалуйста, помогите

1 Ответ

0 голосов
/ 20 июня 2020

для доступа к определенным именам (имена с пространством имен) вы должны использовать средство доступа:

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)
...