从String中删除key = value?

时间:2015-09-17 21:20:18

标签: java string replace replaceall

我有一个像这样的字符串:

<Hello version="100" xsi:schemaLocation="http://www.hello.org/abcss-4_2 http://www.hello.org/v4-2/abcss-4-2.xsd">
 <DataHolder numberOfFields="67">
  <ClientField name="target" pptype="aligning" dataType="string">
   <Value value="panel_3646"/>
   <Value value="panel_3653"/>
  </ClientField>
  <ClientField name="category_count" pptype="symetrical" dataType="double"/>
  <ClientField name="pme.age" pptype="symetrical" dataType="double"/>
  <ClientField name="pme.gender" pptype="aligning" dataType="string">
   <Value value="F"/>
   <Value value="TRE"/>
  </ClientField>
 </DataHolder>
</Hello>

我需要从上面的String中删除这个key = value :: xsi:schemaLocation="http://www.hello.org/abcss-4_2 http://www.hello.org/v4-2/abcss-4-2.xsd对,删除后它将是这样的:

<Hello version="100">
 <DataHolder numberOfFields="67">
  <ClientField name="target" pptype="aligning" dataType="string">
   <Value value="panel_3646"/>
   <Value value="panel_3653"/>
  </ClientField>
  <ClientField name="category_count" pptype="symetrical" dataType="double"/>
  <ClientField name="pme.age" pptype="symetrical" dataType="double"/>
  <ClientField name="pme.gender" pptype="aligning" dataType="string">
   <Value value=""/>
   <Value value="F   "/>
   <Value value="NA"/>
  </ClientField>
 </DataHolder>
</Hello>

我尝试过这个并不起作用:

String textToRemove = "xsi:schemaLocation=\"http://www.hello.org/abcss-4_2 http://www.hello.org/v4-2/abcss-4-2.xsd\"";
String data = readFromFile("path", "filename.xml");
data = data.replaceAll("(?i)\\b" + textToRemove + "\\b", "");
System.out.println(data);

我尝试了像这样的XML解析器,它在我不想要的文件前面添加了XML标记:

Element rootElement = document.getDocumentElement();
rootElement.removeAttribute("xsi:schemaLocation");

Transformer transformer = TransformerFactory.newInstance().newTransformer();
Result output = new StreamResult(new File("output.txt"));
Source input = new DOMSource(document);

transformer.transform(input, output);

更新: -

这是完整的东西。

<Hello version="100" xmlns="http://www.hello.org/abcss-4_2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.hello.org/abcss-4_2 http://www.hello.org/v4-2/abcss-4-2.xsd">

1 个答案:

答案 0 :(得分:1)

已更新,以便将新要求与[校样](https://regex101.com/r/iP8sD3/1)匹配。

GridView