- 我需要替换字符串中的 XML 标记。问题是一些响应没有给我 XML 标签
<?xml version="1.0" encoding="UTF-8"?>
一开始和其中一些 做。 - 有回复,有大写和小写字母。因此,如果我与 String.replace() 匹配,它会忽略它。
- 我需要向该响应添加 XLS 标记。 (目前正在工作)
响应1.开头没有XML标签
<records>
<message>Something was found</message>
</records>
响应 2. 使用 XML 标记(来自其他服务)
<?xml version="1.0" encoding="UTF-8"?>
<records>
<message>Nothing found</message>
</records>
响应 3. 使用 XML 标记(小写 utf-8)
<?xml version="1.0" encoding="utf-8"?>
<records>
<message>Nothing found</message>
</records>
当我添加 XLS 标签时,最终产品需要如下所示:
<?xml-stylesheet type="text/xsl" href="C:\Template.xsl"?>
<?xml version="1.0" encoding="UTF-8"?>
<records>
<message>Nothing found</message>
</records>
目前我正在使用String.replace(),并且匹配
String xlsSchema = "<?xml-stylesheet type=\"text/xsl\" href=\"" + template.getAbsolutePath() + "\"?>";
String replacable = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
String finalTags = replacable + xlsSchema;
result = integrationResponse.replace(replacable, finalTags);
- “可替换”的问题是,一些回复给了我大写字母和一些小写字母。使用
.toUppercase() || .toLowerCase()
不是一个选项,因为它会影响所有 xml 响应。
有没有办法可以创建以下表达式?
如果以 OR 开头 "<?xml"
标签在开头,然后只在其前面添加XLS,如果!包含,则添加XLS架构+ XML标签?
已解决! comment here
最佳答案
已解决! 做了这个/w 正则表达式。
String xlsSchema = "<?xml-stylesheet type=\"text/xsl\" href=\"" + template.getAbsolutePath() + "\"?>";
String newTag = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
String tag = "<?xml";
String strippedXML = "";
// Remove all XML tags from beginning
if (integrationResponse.toLowerCase().contains(tag)) {
strippedXML = integrationResponse.replaceAll("<\\?[^>]*\\?>", "");
result = newTag + xlsSchema + strippedXML;
}
else
result = newTag + xlsSchema + integrationResponse;
关于java - 如何替换字符串中的 XML 标签? (还要检查它是否以 xml 标签开头),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32452605/