简体   繁体   中英

Groovy: How to check multiple tag value in xml?

I have xml content like this:

<?xml version="1.0" encoding="UTF-8"?><service>
  <rs>
    <Id>
      <details>
        <start>2017-10-07</start>
        <startDate>2017-02-02</startDate>
        <endDate>2017-03-02</endDate>
        <runAs>false</runAs>
        <makeVersion>1</makeVersion>
        <patch>this is  patch</patch>
        <parameter>1</parameter>
      </details>
    </Id>
    <person>
      <details>
        <start>2017-09-07</start>
        <startDate>2017-02-02</startDate>
        <endDate>2017-03-02</endDate>
        <runAs>true</runAs>
        <makeVersion>1</makeVersion>
        <patch>this is  patch</patch>
        <parameter>1</parameter>
      </details>
    </person>
  </rs>
  <country>
  <details>
        <start>2017-09-07</start>
        <startDate>2017-02-02</startDate>
        <endDate>2017-03-02</endDate>
        <runAs>true</runAs>
        <makeVersion>1</makeVersion>
        <patch>this is  patch</patch>
        <parameter>1</parameter>
      </details>
  </country>
</service>

and i want to check each start tag value and then update value of runAs i have tried this :

  def xml = new XmlParser().parseText(content)
            def start=xml.'**'.details.start[0].text();
            def  run=xml.'**'.details.start[0].text();
            if(start!=currentDate &&  run!='false'){

                xml.'**'.details.runAs[0].value="false";
            }
           else {
                xml.'**'.details.find({p->

                    p.start[0].value= subtractDays(p.start[0].text(),p.parameter[0].text()).toString()
                    p.runAs[0].value='false';
                })


            }
            def newxml=XmlUtil.serialize(xml)

But it has updated only rs->Id->details->runAs value, what should I change to update every runAs tag value and in certain case update every start tag values too?

You can just change the runAs element value to false using below code:

//Pass xml as string to parseText method
def xml = new XmlSlurper().parseText(xmlString)
//Find runAs element and change value to false
xml.'**'.findAll{it.name() == 'runAs'}.collect{it.replaceBody false}
println groovy.xml.XmlUtil.serialize(xml)

You can quickly try it online demo

In the same way, you can change the value of start element value as well by providing the condition in side findAll closure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM