简体   繁体   English

通过lambda java8转换xml字符串

[英]transform xml string by lambda java8

I have String as XML. 我有String作为XML。 I'm trying to transform String by regexp: 我正在尝试通过正则表达式转换String

public String replaceValueByTag(final String source, String tag, String value) {
     return replaceFirst(source, "(?<=<" + tag + ">).*?(?=</" + tag + ">)", value);
}

then create map with tag, new value: 然后使用新值标签创建地图:

Map<String, String> params = TAGS.stream().collect(toMap(tag -> tag, tag -> substringByTag(request, tag)));

and use map to replace values in XML: 并使用map替换XML中的值:

public String getConfirm(String request) {
    String[] answer = {template}; 
    Map<String, String> params = TAGS.stream().collect(toMap(tag -> tag, tag -> substringByTag(request, tag)));   
    params.entrySet().forEach(entry -> answer[0] = replaceValueByTag(answer[0], entry.getKey(), entry.getValue()));
    return answer[0];
}

How to write lambda expression without saving in array (lambda takes String , converts it by map and returns a String )? 如何在不保存数组的情况下编写lambda表达式(lambda使用String ,通过map转换并返回String )?

You can use reduce to apply all the elements of the Stream of map entries on your template String. 您可以使用reducetemplate条目Stream的所有元素应用于template字符串。

I'm not sure, though, how the combiner should look like (ie how to combine two partially transformed String s into a String that contains all transformations), but if a sequential Stream is sufficient, you don't need the combiner: 不过,我不确定合并combiner外观(即如何将两个部分转换的String合并为包含所有转换的String ),但是如果顺序Stream足够,则不需要合并器:

String result = 
    params.entrySet()
          .stream()
          .reduce(template,
                  (t,e) -> replaceValueByTag(t, e.getKey(), e.getValue()),
                  (s1,s2)->s1); // dummy combiner

instead of using an intermediate map you could directly apply the terminal operation, I'll use the .reduce() operation like @Eran suggested: 除了使用中间映射,您可以直接应用终端操作,而使用@red建议的.reduce .reduce()操作:

String result = TAGS.stream()
     .reduce(
         template, 
         (tmpl, tag) -> replaceValueByTag(tmpl, tag, substringByTag(request, tag),
         (left, right) -> left) // TODO: combine them
     );

This way you wont have as much overhead. 这样,您将没有太多的开销。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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