简体   繁体   English

如何将xml节点(作为字符串)附加到现有的XML Element节点(仅使用java内置函数)?

[英]How to append xml nodes (as a string) into an existing XML Element node (only using java builtins)?

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

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. 为了将字符串解析为xml节点然后将它们附加到节点,我尝试使用documentFragment但是我无法到达任何地方。 In short, I need something as easy as .NET's .innerXML but it's not in the java api. 简而言之,我需要像.NET的.innerXML一样简单,但它不在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 ? 如何在不使用任何第三方库的情况下执行此操作?

[EDIT] It's not obvious in the example but I'm not supposed to know the content of variable 'nodesToAppend'. [编辑]在示例中并不明显,但我不应该知道变量'nodesToAppend'的内容。 So please, don't point me to tutorials about how to create elements in an xml document. 所以,请不要指向有关如何在xml文档中创建元素的教程。

You can do this in java - you should be able to derive the Rhino equivalent: 你可以在java中做到这一点 - 你应该能够得到Rhino等价物:

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

Since doc and doc2 are two different Document s the trick is to import the node from one document to another, which is done with the importNode api above 由于docdoc2是两个不同的Document因此诀窍是将节点从一个文档导入另一个文档,这是通过上面的importNode api完成的。

I think your question is like this question and there is answer on it : Java: How to read and write xml files? 我认为你的问题就像这个问题,并且有答案: Java:如何读取和写入xml文件?

OR see this link http://www.mkyong.com/java/how-to-create-xml-file-in-java-dom/ 或者看到这个链接http://www.mkyong.com/java/how-to-create-xml-file-in-java-dom/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM