【问题标题】:How to replace XML tag in String? (also checking if it starts with xml tag)如何替换字符串中的 XML 标记? (还检查它是否以 xml 标签开头)
【发布时间】:2015-09-08 08:16:18
【问题描述】:
  1. 我需要替换字符串中的 XML 标记。问题是一些响应在开头没有给我 XML 标签<?xml version="1.0" encoding="UTF-8"?>,其中一些 做。
  2. 有响应,有大写和小写字母。所以如果我匹配 String.replace() 它会忽略它。
  3. 我需要在该响应中添加 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);
  • 'replacable' 的问题在于,一些回复给了我大写和一些小写字母。使用 .toUppercase() || .toLowerCase() 不是一个选项,因为它会影响所有 xml 响应。

有没有办法可以创建以下表达式? 如果以OR contains开头"&lt;?xml"标签,则只在其前添加XLS,如果!contains,则添加XLS架构+XML标签?

已解决! comment here

【问题讨论】:

  • 这里的上下文是什么?通常,任何弄乱 XML 文档的字符串表示的做法都是一个非常糟糕的主意……只需在 XML API 中解析 XML 并使用结果。
  • 看看这里stackoverflow.com/a/5055036/529256 演示不区分大小写的查找/替换。
  • @Kefirchiks 你应该把它作为你问题的答案,它在 cmets 区域难以辨认。另外,很高兴能帮上忙,请点赞我的回答。谢谢。

标签: java xml string xls


【解决方案1】:

已解决! 这是 /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;

【讨论】:

    【解决方案2】:

    您可以像这样将 integrationResponse 更改为大写:

    result = integrationResponse.toUppercase().replace(replacable.toUppercase(),finalTags);
    result_ = result.toLowerCase() ;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-08
      • 2015-09-29
      • 2015-09-24
      • 1970-01-01
      • 2012-05-11
      • 1970-01-01
      • 2016-04-07
      • 1970-01-01
      相关资源
      最近更新 更多