繁体   English   中英

通过lambda java8转换xml字符串

[英]transform xml string by lambda java8

我有String作为XML。 我正在尝试通过正则表达式转换String

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

然后使用新值标签创建地图:

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

并使用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];
}

如何在不保存数组的情况下编写lambda表达式(lambda使用String ,通过map转换并返回String )?

您可以使用reducetemplate条目Stream的所有元素应用于template字符串。

不过,我不确定合并combiner外观(即如何将两个部分转换的String合并为包含所有转换的String ),但是如果顺序Stream足够,则不需要合并器:

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

除了使用中间映射,您可以直接应用终端操作,而使用@red建议的.reduce .reduce()操作:

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

这样,您将没有太多的开销。

暂无
暂无

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

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