在java,dom,xml解析中设置新节点值的问题 [英] Problems setting a new node value in java, dom, xml parsing

查看:92
本文介绍了在java,dom,xml解析中设置新节点值的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

DocumentBuilder dBuilder = dbFactory_.newDocumentBuilder();
StringReader reader = new StringReader(s);
InputSource inputSource = new InputSource(reader);
Document doc_ = dBuilder.parse(inputSource);

然后我想在该节点的根节点下用该代码创建一个新元素:

and then I would like to create a new element in that node right under the root node with this code:

Node node = doc_.createElement("New_Node");
node.setNodeValue("New_Node_value");
doc_.getDocumentElement().appendChild(node);

问题是节点被创建和追加,但是值没有设置。我不知道我是否看不到值,当我看到我的xml,如果它隐藏在某种方式,但我不认为是这样的情况,因为我尝试获取节点值后创建节点调用并返回 null
我是xml和dom的新手,我不知道新节点的值在哪里存储。这是一个属性吗?

The problem is that the node gets created and appended but the value isn't set. I don't know if I just can't see the value when I look at my xml if its hidden in some way but I don't think that's the case because I've tried to get the node value after the create node call and it returns null. I'm new to xml and dom and I don't know where the value of the new node is stored. Is it like an attribute?

<New_Node value="New_Node_value" />

或者是在这里放值:

<New_Node> New_Node_value </New_Node>

任何帮助将不胜感激,

谢谢,Josh

推荐答案

以下代码:

Element node = doc_.createElement("New_Node");
node.setTextContent("This is the content");  //adds content
node.setAttribute("attrib", "attrib_value"); //adds an attribute

产生:

<New_Node attrib="attrib_value">This is the content</New_Node>

希望澄清。

这篇关于在java,dom,xml解析中设置新节点值的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆