Best way to convert xml to have CDATA around text (in java)

前端 未结 4 585
[愿得一人]
[愿得一人] 2021-01-23 02:14

I have a weird requirement where I need to take some xml and re-write it so that the text nodes are wrapped in CDATA (this is for a client that won\'t allow normal escaping).

4条回答
  •  逝去的感伤
    2021-01-23 02:40

    Thanks for all of your answers. I found a way to do this using dom4j. My implementation does not work if elements have "mixed" children (i.e. text element), but in my case this isn't a problem. It works because dom4j will output CDATA if you add CDATA nodes:

        public void replaceTextWithCdataNoMixedText(Document doc) {
            if( doc == null )
                return;
            replaceTextWithCdata(doc.content());
        }
    
        private void replaceTextWithCdata(List content) {
            if (content == null)
                return;
            for (Object o : content) {
                if (o instanceof Element) {
                    Element e = (Element) o;
                    String t = e.getTextTrim();
                    if (textNeedsEscaping(t)) {
                        e.clearContent();
                        e.addCDATA(t);
                    } else {
                        List childContent = e.content();
                        replaceTextWithCdata(childContent);
                    }
                }
            }
        }
    
    
        private boolean textNeedsEscaping(String t) {
            if (t == null)
                return false;
            for (int i = 0; i < t.length(); i++) {
                char c = t.charAt(i);
                if (c == '<' || c == '>' || c == '&') {
                    return true;
                }
            }
            return false;
        }
    

提交回复
热议问题