Search code examples
javastringreplacereplaceall

remove key=value from a String?


I have a String which is like this:

<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>

I need to remove this key=value:: xsi:schemaLocation="http://www.hello.org/abcss-4_2 http://www.hello.org/v4-2/abcss-4-2.xsd pair from my above String and after the removal it will be like this:

<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>

I tried this and it doesn't work:

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);

I tried XML parser way like this which is appending XML tag in front of the file which I dont want:

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);

Update:-

This is the full stuff.

<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">

Solution

  • Updated to match newer requirements with a [proof] (https://regex101.com/r/iP8sD3/1).

    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(textToRemove, "");
    System.out.println(data);