Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
161 views
in Technique[技术] by (71.8m points)

Groovy split results

Script:

import com.sap.gateway.ip.core.customdev.util.Message;
    import java.util.HashMap;
    import groovy.xml.XmlUtil;
    import groovy.xml.StreamingMarkupBuilder;
    import groovy.xml.*;
    
    def Message processData(Message message) {
    
         // get body
        def body = message.getBody(java.io.Reader);
        
        // parse xml body
        def result = new XmlSlurper().parse(body);
    
        def message1 = result.Message1;
        def message2 = result.Message2;
    
    def one = message1.EmployeeDataReplicationConfirmation.EmployeeDataReplicationConfirmation.collect { it.personId.text() }
    def two = message2.queryCompoundEmployeeResponse.CompoundEmployee.collect { it.person.person_id.text() }
    def intersect = one.intersect(two)
    def userid1 = ((one - intersect) + (two - intersect))
    println((one - intersect) + (two - intersect))
    return message;


     

Output:

Console Output
Running...
[6107, 10140, 11774]

In the text 1 and text2 fields are different ids. This command will give me IDs that are the same in both. But he gives them to me like this:[6107, 10140, 11774] But i need it in XML.. like .. I need this

<Person>
    <User>
    <userid>6107</userid>
    </User>
    <User>
    <userid>10140</userid>
    </User>
    <User>
    <userid>11774</userid>
    </User>

how can i do it ? Thanks :)

question from:https://stackoverflow.com/questions/65900544/groovy-split-results

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use the MarkupBuilder class to create your XML, imagine you already have your data ready, then the only thing you need to do is:

import groovy.xml.MarkupBuilder

def userIds = [6107, 10140, 11774]

def xml = new StringWriter()
def builder = new MarkupBuilder(xml)

builder.people() {
   userIds.each { id ->
     user() {
      userId(id)
     }
  }
}

println xml

This will be the output

<people>
  <user>
    <userId>6107</userId>
  </user>
  <user>
    <userId>10140</userId>
  </user>
  <user>
    <userId>11774</userId>
  </user>
</people>

For more examples of working with XML, you can see my gist Working with xml


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...