我想使用groovy
根据输入标记中出现的第n次特殊字符来分割xml标记我有一个xml输入与许多标签持有巨大的数据。我想使用groovy根据输入标记中出现的第n个特殊字符来分割xml标记。
如何在Java中每次出现第n个字符时拆分字符串—此逻辑适用于我,但适用于一个xml标记。我有多个xml标记,并希望根据分隔符'/'的第四次出现来分割所有标记。
能告诉我怎么做吗?谢谢。
示例输入xml:
<Row>
<EntityID>9035158701/9035158702/9035158703/9035158704/9035158705/9035158706/9035158707/9035158708/9035158709/9035158710</EntityID>
<RefID>7U2HYUTP/5Z1IWGUS/7AK9MDDJ/6RP9DXAW/29FBRBEL/5YKDCO3B/75MUQU7S/57QCGOQE/2EUX64ON/2VTJPVUV</RefID>
</Row>
预期输出:
<Root>
<Row>
<EntityID>9035158701/9035158702/9035158703/9035158704</EntityID>
<RefID>7U2HYUTP/5Z1IWGUS/7AK9MDDJ/6RP9DXAW</RefID>
</Row>
<Row>
<EntityID>9035158705/9035158706/9035158707/9035158708</EntityID>
<RefID>29FBRBEL/5YKDCO3B/75MUQU7S/57QCGOQE</RefID>
</Row>
<Row>
<EntityID>9035158709/9035158710</EntityID>
<RefID>2EUX64ON/2VTJPVUV</RefID>
</Row>
</Root>
import com.sap.gateway.ip.core.customdev.util.Message;
import java.util.HashMap;
import groovy.xml.*;
def Message processData(Message message) {
def body = message.getBody(java.io.Reader)
assert body != null
def input = new XmlSlurper().parse(body);
def entityid = input.EntityID.text();
def refid = input.RefID.text();
int nth=0;
int cont=0;
def writer = new StringWriter()
for(int i=0;i<entityid.length();i++){
if(entityid.charAt(i)=='/')
nth++;
if(nth == 4 || i==entityid.length()-1){
new MarkupBuilder(writer).Row{
if(i==entityid.length()-1) //with this if you preveent to cut the last number
EntityID (entityid.substring(cont,i+1))
else
EntityID (entityid.substring(cont,i+1))
nth=0;
cont =i+1;
}
}
}
def output = writer.toString()
message.setBody(output)
return message;
}
您可以使用split
将字符串用一个字符分隔,然后使用collate
将它们批成组,然后使用join
将每组中的元素批成组,transpose
将Entity和Ref id批成行:
def processData(String input) {
def parsed = new XmlParser().parseText(input)
def eids = parsed.EntityID.text().split("/").collate(4)*.join("/")
def rids = parsed.RefID.text().split("/").collate(4)*.join("/")
StringWriter writer = new StringWriter()
new MarkupBuilder(writer).Root {
[eids, rids].transpose().each { eid, rid ->
Row {
EntityID(eid)
RefID(rid)
}
}
}
writer.toString()
}
它接受一个String并返回一个String,因此您需要将它与Message类集成(如上所述)
def input = '''<Row>
<EntityID>9035158701/9035158702/9035158703/9035158704/9035158705/9035158706/9035158707/9035158708/9035158709/9035158710</EntityID>
<RefID>7U2HYUTP/5Z1IWGUS/7AK9MDDJ/6RP9DXAW/29FBRBEL/5YKDCO3B/75MUQU7S/57QCGOQE/2EUX64ON/2VTJPVUV</RefID>
</Row>'''
processData(input)
返回<Root>
<Row>
<EntityID>9035158701/9035158702/9035158703/9035158704</EntityID>
<RefID>7U2HYUTP/5Z1IWGUS/7AK9MDDJ/6RP9DXAW</RefID>
</Row>
<Row>
<EntityID>9035158705/9035158706/9035158707/9035158708</EntityID>
<RefID>29FBRBEL/5YKDCO3B/75MUQU7S/57QCGOQE</RefID>
</Row>
<Row>
<EntityID>9035158709/9035158710</EntityID>
<RefID>2EUX64ON/2VTJPVUV</RefID>
</Row>
</Root>