0

I need to replace namespace with some value

     private static String REGEX1 = "(<\\/?)[ns2]+?:";

    private static String INPUT = "<ns1:fso xmlns:ns2='https://www.example.com/fsoCanonical'><ns2:senderId xmlns='http://www.example.com/fsoCanonical'>abc</ns2:senderId><receiverId xmlns='http://www.example.com/fsoCanonical'>testdata</receiverId>   <messageId xmlns='http://www.example.com/fsoCanonical'>4CF4DC05126A0077E10080000A66C871</messageId>    </ns1:fso> ";
    private static String REPLACE = "$1cc:";

    public static void main(String[] args) {
                Pattern p = Pattern.compile(REGEX1);
                Matcher m = p.matcher(INPUT); // get a matcher object
                StringBuffer sb = new StringBuffer();
                while (m.find()) {
                 m.appendReplacement(sb, REPLACE);
               }
                m.appendTail(sb);
              System.out.println(sb.toString());

I need to replace my namespace from ns2 to cc but the above code can replace only the ns2: to cc: and I need to replace the tag with xmlns:ns2= with xmlns:cc= also. Please advise how to replace this using the same regex condition.

         <ns1:fso xmlns:ns2='https://www.example.com/fsoCanonical'><ns2:senderId xmlns='http://www.example.com/fsoCanonical'>abc</ns2:senderId><receiverId xmlns='http://www.example.com/fsoCanonical'>testdata</receiverId>   <messageId xmlns='http://www.example.com/fsoCanonical'>4CF4DC05126A0077E10080000A66C871</messageId>    </ns1:fso> "

to

      <ns1:fso xmlns:cc='https://www.example.com/fsoCanonical'><cc:senderId xmlns='http://www.example.com/fsoCanonical'>abc</cc:senderId><receiverId xmlns='http://www.example.com/fsoCanonical'>testdata</receiverId>   <messageId xmlns='http://www.example.com/fsoCanonical'>4CF4DC05126A0077E10080000A66C871</messageId>    </ns1:fso> "
user3428736
  • 864
  • 2
  • 13
  • 33
  • 1
    Why would you use a regular expression for this rather than an XML library? Use the right tool for the job. You really, really don't want to try writing a regular expression to parse XML. – Jon Skeet Apr 15 '17 at 08:37
  • Don't parse XML using regex; use a real parser. See [**How to retrieve element value of XML using Java?**](http://stackoverflow.com/questions/4076910/how-to-retrieve-element-value-of-xml-using-java) or [**How to read XML using XPath in Java**](http://stackoverflow.com/questions/2811001/how-to-read-xml-using-xpath-in-java) – kjhughes Apr 15 '17 at 13:07

0 Answers0