srinannapa
srinannapa

Reputation: 3207

XML String replacement

How can I replace String in xml ..

I've

<schema>src/main/castor/document.xsd</schema>

I need to replace to

<schema>cs/src/main/castor/document.xsd</schema>

If I use simple , xmlInStr is the string form of xml document

xmlInStr.replaceAll(
   "src/main/castor/GridDocument.xsd",    
   "correspondenceCastor/src/main/castor/GridDocument.xsd"
); 

I Tried replace instead ,

xmlInStr.replace("src/main/castor/GridDocument.xsd".toCharArray().toString(), "correspondenceCastor/src/main/castor/GridDocument.xsd".toCharArray().toString());

it's not working . any clues

Managed like this

int indx = from.indexOf(from); xmlInStr = xmlInStr.substring(0,indx) + to + xmlInStr.substring(indx + from.length());

Upvotes: 0

Views: 1515

Answers (4)

AlexR
AlexR

Reputation: 115388

You can use repalce or replaceAll. Anyway you have to use the value returned by this method. The method does not modify the string itself because String class is immutable.

Upvotes: 1

Sergei Tachenov
Sergei Tachenov

Reputation: 24919

Both replace() and replaceAll() don't actually replace anything in the string (strings are immutable). They return a new string instead, but you just discard the return value, that's why you don't see it anywhere. By the way, that .toCharArray().toString() looks completely useless to me. A character literal is already a full-fledged String.

But you really should use an XML parser instead. Unless your task is very simple and you're absolutely sure that you don't replace anything that shouldn't be replaced.

Upvotes: 0

user177800
user177800

Reputation:

You use an XML parser to parse and manipulate XML, don't try and use regular expression based string replacement mechanisms it will not work and will only bring pain and suffering.

Upvotes: 2

khachik
khachik

Reputation: 28703

String.replaceAll takes a regular expression as the first argument. Use replace instead.

Upvotes: 3

Related Questions