仅使用java内置函数

仅使用java内置函数

本文介绍了如何将xml节点(作为字符串)附加到现有的XML Element节点(仅使用java内置函数)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(免责声明:在RingoJS中使用Rhino)

(Disclaimer: using Rhino inside RingoJS)

假设我有一个包含元素的文档,我不知道如何将节点作为字符串附加到此元件。为了将字符串解析为xml节点然后将它们附加到节点,我尝试使用documentFragment,但我无法到达任何地方。简而言之,我需要像.NET的.innerXML一样简单,但它不在java api中。

Let's say I have a document with an element , I don't see how I can append nodes as string to this element. In order to parse the string to xml nodes and then append them to the node, I tried to use documentFragment but I couldn't get anywhere. In short, I need something as easy as .NET's .innerXML but it's not in the java api.

var dbFactory = javax.xml.parsers.DocumentBuilderFactory.newInstance();
var dBuilder = dbFactory.newDocumentBuilder();
var doc = dBuilder.newDocument();
var el = doc.createElement('test');
var nodesToAppend = '<foo bar="1">Hi <baz>there</baz></foo>';
el.appendChild(???);

如何在不使用任何第三方库的情况下执行此操作?

How can I do this without using any third party library ?

在示例中并不明显,但我不应该知道变量'nodesToAppend'的内容。所以,请不要指向有关如何在xml文档中创建元素的教程。

It's not obvious in the example but I'm not supposed to know the content of variable 'nodesToAppend'. So please, don't point me to tutorials about how to create elements in an xml document.

推荐答案

你可以在java - 你应该能够得到Rhino等价物:

You can do this in java - you should be able to derive the Rhino equivalent:

DocumentBuilderFactory dbFactory = javax.xml.parsers.DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.newDocument();
Element el = doc.createElement('test');
doc.appendChild(el);


String xml = "<foo bar=\"1\">Hi <baz>there</baz></foo>";
Document doc2 = builder.parse(new ByteArrayInputStream(xml.getBytes()));

Node node = doc.importNode(doc2.getDocumentElement(), true);
el.appendChild(node);

由于 doc doc2 是两个不同的文档,诀窍是将节点从一个文档导入到另一个文档,这是通过 importNode api高于

Since doc and doc2 are two different Documents the trick is to import the node from one document to another, which is done with the importNode api above

这篇关于如何将xml节点(作为字符串)附加到现有的XML Element节点(仅使用java内置函数)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 20:43