XML DOM setTextContent

时间:2013-12-03 16:32:42

标签: java xml dom

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

我试过了:

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

但我的结果是:

<titleproper> Bla bla text lt;num;gt;1lt;/numgt;</titleproper>

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

1 个答案:

答案 0 :(得分:0)

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

// 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);