Amruit Pratyay
Amruit Pratyay

Reputation: 67

How do I change the quotes on xml Declaration using Java File Handling?

I currently have a bunch of XML files and the task was to change the text under a specific element. So, in my logic, I was fetching the root element, getting its children and then for the specific children element, I was using setText() method to change the content of it. Now the only issue is, the XML declaration which initially was:

<?xml version='1.0' encoding='UTF-8'?>

changes to:

<?xml version="1.0" encoding="UTF-8"?>

I tried creating a string buffer and replacing the line, but for some reason it's not working. The code for it was as follows:

StringBuffer buffer = new StringBuffer();
while (sc.hasNextLine()) {
    buffer.append(sc.nextLine()+System.lineSeparator());
}
String fileContents = buffer.toString();
sc.close();
String oldLine = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
String newLine = "<?xml version=\'1.0\' encoding=\'UTF-8\'?>";
try {
    fileContents = fileContents.replaceAll(oldLine, newLine);
}
catch(Exception e) {
    System.out.println("Not Changed");
}

Does anyone know an approach that could work for this scenario?

Upvotes: 0

Views: 98

Answers (1)

Abra
Abra

Reputation: 20914

Method replaceAll treats its first argument as a regular expression.

The question mark (i.e. ?) is a metacharacter but you want to treat it as a normal character.

You have two options:

  1. Call method replace rather than method replaceAll.
  2. Escape the question marks by preceding them with a [double] backslash (i.e. \)
String oldLine = "<\\?xml version=\"1.0\" encoding=\"UTF-8\"\\?>";
String newLine = "<?xml version=\'1.0\' encoding=\'UTF-8\'?>";
fileContents = fileContents.replaceAll(oldLine, newLine);

Upvotes: 1

Related Questions