[英]Java: remove < and > from text in XML (not tags)
我很難轉義 xml 以供 Java 處理。 我正在使用 JTidy 來轉義不需要的字符,但很難從<tag> capacity < 1000 </tag>
等值中刪除“<”和“>”
我正在使用下面的代碼來轉義輸入
public String CleanXML(String input){
Tidy tidy = new Tidy();
tidy.setInputEncoding("UTF-16");
tidy.setOutputEncoding("UTF-16");
tidy.setWraplen(Integer.MAX_VALUE);
tidy.setXmlOut(true);
tidy.setSmartIndent(true);
tidy.setXmlTags(true);
tidy.setMakeClean(true);
tidy.setForceOutput(true);
tidy.setQuiet(true);
tidy.setShowWarnings(false);
StringReader in = new StringReader(input);
StringWriter out = new StringWriter();
tidy.parse(in, out);
return out.toString();
}
使用以下功能
private static final Pattern TAG_REGEX = Pattern.compile("<tag>(.+?)</tag>", Pattern.DOTALL);
public String CleanXML(String input){
final Matcher matcher = TAG_REGEX.matcher(input);
while (matcher.find()) {
String value = matcher.group(1);
String valueReplace = value.replaceAll("[^a-zA-Z0-9\\s]", "");
input.replace(value,valueReplace);
}
return input;
}
它使用正則表達式搜索來獲取標簽之間的值,然后刪除所有非字母數字字符。 正則表達式和基本思想是從Java regex中獲得的, 用於提取標簽之間的文本
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.