1

我正在尝试将我在 ActionScript 中编写的函数移植到 Java,但遇到了一些麻烦。我已经包含了下面的功能。我找到了对问题 #375420的回复,但我真的需要编写一个单独的课程吗?谢谢。

public static function replaceXML(str:String):String {
  return str.replace(/[\"'&<>]/g, function($0:String):String {
    return StringUtil.substitute('&#{0};', $0.charCodeAt(0));
  });
}

输入

<root><child id="foo">Bar</child></root>

输出

&#60;root&#62;&#60;child id=&#34;foo&#34;&#62;Bar&#60;/child&#62;&#60;/root&#62;

更新

如果有人想知道,这是我的解决方案。感谢Sri Harsha Chilakapati

public static String replaceXML(final String inputStr) {
  String outputStr = inputStr;
  Matcher m = Pattern.compile("[&<>'\"]").matcher(outputStr);
  String found = "";
  while (m.find()) {
    found = m.group();
    outputStr = outputStr.replaceAll(found,
      String.format("&#%d;", (int)found.charAt(0)));
  }
  return outputStr;
}
4

2 回答 2

1

Java 是一种面向对象的语言,因此使用对象。通常,您可以创建一个 Util 类,例如RegExUtil并提供一个静态方法来从任何其他类调用该方法。util 类本身不应该被实例化。您可以使用私有构造函数来实现。

public class RegExUtil {

  private RegExUtil(){
    //do nth.
  }

  public static String replaceXML(String input){
    //do sth.
  }
}

您应该首先查找 Apache Commons,因为它们可能已经为您的目标提供了解决方案,或者至少您看到了 Util 类是如何组成的。

于 2013-04-22T11:16:10.497 回答
1

您可以为此使用正则表达式。

import java.util.regex.Matcher;
import java.util.regex.Pattern;

String myString = "<root><child id=\"foo\">Bar</child></root>";

Matcher m = Pattern.compile("[^\\p{L}\\p{N};\"+*/-]").matcher(myString);

while (m.find()) {
    String found = m.group();
    myString = myString.replaceAll(found, "&#" + (int)found.charAt(0) + ";");
}

System.out.println(myString);

它正在工作。

输出是

&#60;root&#62;&#60;child&#32;id&#61;"foo"&#62;Bar&#60;/child&#62;&60;/root&#62;
于 2013-04-22T11:29:41.953 回答