Groovy:如何检查xml中的多个标记值?

时间:2017-10-24 12:21:25

标签: xml groovy xmlslurper

我有这样的xml内容:

<?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>

我想检查每个开始标记值,然后更新runAs的值,我试过这个:

  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)

但它只更新了rs-&gt; Id-&gt;详细信息 - &gt; runAs值,我应该更改什么来更新每个runAs标记值,并且在某些情况下也会更新每个开始标记值?

1 个答案:

答案 0 :(得分:1)

您只需使用以下代码将runAs元素值更改为false

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

您可以在线快速尝试 demo

同样,您可以通过在start封闭边提供条件来更改findAll元素值的值。