Reputation: 67
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
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:
replaceAll
.\
)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