【问题标题】:parsing xml with namespace in groovy在groovy中使用名称空间解析xml
【发布时间】:2020-06-20 17:31:48
【问题描述】:

我有以下 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 groovy xml-parsing xml-namespaces


    【解决方案1】:

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

    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)
    

    【讨论】:

      猜你喜欢
      • 2011-04-07
      • 1970-01-01
      • 2012-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-30
      • 1970-01-01
      • 2021-05-03
      相关资源
      最近更新 更多