XML DOM setTextContent

我需要将一个大的XML拆分成许多child.xml文件。 我的代码工作,除了更改值。 我需要在现有元素titleproper插入我的String Titleproper Bla bla text X

我试过了:

 header.getElementsByTagName("titleproper").item(0).setTextContent(Titleproper); 

但我的结果是:

  Bla bla text lt;num;gt;1lt;/numgt; 

我理解为什么,但我不知道如何欺骗这个限制。 我需要在我的titleproper插入Text + Xml代码。

如果Titleproper字符串是XML本身,那么您需要解析此XML并将结果节点插入目标树。 org.w3c.dom.ls接口可以帮助您。

 // we need to get the DOMImplementation from the Document - if header is an // Element then do: DOMImplementationLS ls = (DOMImplementationLS)header.getOwnerDocument().getImplementation(); // if header is already a Document then it's just //DOMImplementationLS ls = // (DOMImplementationLS)header.getImplementation(); // LSInput represents the source from which the XML to be parsed will be taken LSInput input = ls.createLSInput(); input.setStringData(Titleproper); // LSParser does the parsing LSParser parser = ls.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null); // parseWithContext(input, context, action) parses the fragment given by input // and inserts the results at a position relative to the node "context". In this // case we use ACTION_REPLACE_CHILDREN which means remove all the child nodes // (if any) from the context node and replace them with the result of the parse. // Alternative actions include replacing the context node entirely, inserting // the parse results as siblings before or after the context node, etc. parser.parseWithContext(input, header.getElementsByTagName("titleproper").item(0), LSParser.ACTION_REPLACE_CHILDREN);