2

charactersI am trying to include the correct characters in an XML document text node:

Element request = doc.createElement("requestnode");
request.appendChild(doc.createTextNode(xml));
rootElement.appendChild(request);

The xml string is a segment of a large xml file which I have read in:

Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("rootnode");
doc.appendChild(rootElement);

<firstname>John</firstname>
<dateOfBirth>28091999</dateOfBirth>
<surname>Doe</surname>

The problem is that passing this into createTextNode is replacing some of the charters:

&lt;firstname&gt;John&lt;/firstname&gt;&#13;
&lt;dateOfBirth&gt;28091999&lt;/dateOfBirth&gt;&#13;
&lt;surname&gt;Doe&lt;/surname&gt;&#13;

Is there any way I can keep the correct characters (< , >) in the textnode. I have read about using importnode but this is not correctly XML, only a segment of a file.

Any help would be greatly appreciated.

EDIT: I need the xml string (which is not fully formatted xml, only a segment of an external xml file) to be in the "request node" as I am building XML to be imported into SOAP UI

4

1 回答 1

2

您不能将元素标记和文本传递给该createTextNode()方法。您只需要传递文本。然后,您需要将此文本节点附加到元素。

如果源是另一个 XML 文档,则必须从一个元素中提取文本节点并将其插入到另一个元素中。您可以抓取一个节点(元素和文本)并尝试作为文本节点插入另一个节点。这就是为什么您会看到所有转义字符。

另一方面,您可以将此 Node 插入到另一个 XML 中(如果允许该结构),应该没问题。

在您的上下文中,我假设“请求”是某种 Node. Node 的子元素可以是另一个元素、文本等。您必须非常具体。

您可以执行以下操作:

Element name = doc.createElement("name");
Element dob = doc.createElement("dateOfBirth");
Element surname = doc.createElement("surname");

name.appendChild( doc.createTextNode("John") );
dob.appendChild( doc.createTextNode("28091999") );
surname.appendChild( doc.createTextNode("Doe") );

然后您可以将这些元素添加到父节点:

node.appendChild(name);
node.appendChild(dob);
node.appendChild(surname);

更新:作为替代方案,您可以打开文档流并将您的 XML 字符串作为字节流插入。像这样的东西(未经测试的代码,但很接近):

String xmlString = "<firstname>John</firstname><dateOfBirth>28091999</dateOfBirth><surname>Doe</surname>";

DocumentBuilderFactory fac = javax.xml.parsers.DocumentBuilderFactory.newInstance();
DocumentBuilder builder = fac.newDocumentBuilder();
Document newDoc = builder.parse(new ByteArrayInputStream(xmlString.getBytes()));
Element newElem = doc.createElement("whatever");
doc.appendChild(newElem);

Node node = doc.importNode(newDoc.getDocumentElement(), true);
newElem.appendChild(node);

像这样的东西应该可以解决问题。

于 2014-11-06T13:50:00.587 回答