0

How to add CDATA in a XML without the Loss of <br/> tag in java?

I need to add the Cdata to the String temp1 and also need to retain the break tag.

Then the program and sample below:

i) program-AddCDATASectionToDOMDocument.java

ii) input xml

iii) required output

i) program-AddCDATASectionToDOMDocument.java

public class AddCDATASectionToDOMDocument {

    public static void main(String[] args) throws Exception {
        xmlreader xmlr = new xmlreader();
        String temp1 = xmlr.xmlFileReader("example.xml", "contentmeta","subtitle");
        String temp2 = "<![CDATA[" + temp1 + "]]>";
        xmlr.xmlFileWriter("example.xml", "contentmeta", "subtitle", temp2);
    }

}

ii)example.xml enter image description here

iii)required out put

enter image description here

0

1 Answer 1

1

How about using regular expressions instead of parsing it with DOM? This code may work with your example:

    String input = new String(Files.readAllBytes(Paths.get("file1.xml")));
    final Pattern regex = Pattern.compile("<subtitle>(.+?)</subtitle>");
    final Matcher matcher = regex.matcher(input);
    String modification;
    if (matcher.find()) {
         modification = "<subtitle><![CDATA["+matcher.group(1)+"]]></subtitle>";
         String output = matcher.replaceFirst(modification);
         System.out.println(output);
         FileOutputStream outputStream = new FileOutputStream("file2.xml");
         outputStream.write(output.getBytes());
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.