创建CDATA部分令人困惑

我试图在描述字段中创建CDATA部分,但失败了。 代码非常简单,但在生成的XML中没有出现CDATA部分!

Node de = document.createElement("description"); de.appendChild(document.createCDATASection(reportData.getIssue().getDescription() + "more]]>data")); e.appendChild(de); 

在结果XML中,我得到:

 Room #1128 has AD issues.more]]>data 

我究竟做错了什么?!

序列]]>终止CDATA部分,因此不能出现在CDATA部分中。

您的XML库正在通过放弃CDATA部分并使用实体来恢复具有特殊含义的字符来恢复。

由于]]>Hello, world>是等价的,这不是问题(除非有人试图解析生成的XML使用不是XML解析器的工具,哪种方式是疯狂的)。

您应该指定CDATA部分元素。

你可以这样做;

  transformer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, "tagName"); 

如果要指定多个CDATA节元素,请使用空格作为分隔符。

 transformer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, "tagName1 tagName2"); 

完整代码

 DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.newDocument(); Element rootElement = doc.createElement("catalog"); doc.appendChild(rootElement); Element description = doc.createElement("description"); description.appendChild(doc.createCDATASection("/&(*/**SOME STRANGE DESCRIPTION**ĞĞÜ656*9/*9^+%3ÜĞPÜ")); rootElement.appendChild(description); Element books = doc.createElement("books"); rootElement.appendChild(books); Element book = doc.createElement("book"); books.appendChild(book); Element author = doc.createElement("author"); author.appendChild(doc.createCDATASection("&/(&/(QNzxB5yiBibGj2MM ÇÖÇÇ")); book.appendChild(author); Element price = doc.createElement("price"); price.appendChild(doc.createTextNode("50.5")); book.appendChild(price); Element title = doc.createElement("title"); title.appendChild(doc.createTextNode("my book title")); book.appendChild(title); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, "description author descr"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(System.out); transformer.transform(source, result); 

结果将是这样的;

       50.5 my book title    

如果我们想要应用您的确切样本(使用您的数据+“]]”);

 String someInfo = "example-info"; Element dscr = doc.createElement("descr"); dscr.appendChild(doc.createCDATASection(someInfo + "more]]>data")); book.appendChild(dscr); 

那么结果会是这样的;

        50.5 my book title data]]>    

使用以下方法:

 CDATASection cdata = document.createCDATASection(""); 

您无法在XML数据中编写>
它正被转移到> (比…更棒)

请注意, 大于号符号会弄乱您的标记,因为它是结束标记的开头。

你可以在这里阅读它(在其他地方)