在Java中解析XML时设置新节点值出现问题

24

我有以下代码:

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

然后,我想使用以下代码在该节点下方的根节点右侧创建一个新元素:

Node node = doc_.createElement("New_Node");
node.setNodeValue("New_Node_value");
doc_.getDocumentElement().appendChild(node);
问题在于节点被创建并附加,但值未设置。我不知道当我查看我的xml时是否只是看不到该值,因为它以某种方式隐藏了,但我认为这不是问题,因为我已尝试在创建节点调用后获取节点值,并返回null。 我对xml和dom都很陌生,不知道新节点的值存储在哪里。它像属性一样吗?
<New_Node value="New_Node_value" />

还是把值放在这里:

<New_Node> New_Node_value </New_Node>

非常感谢您的帮助,

谢谢, Josh


你是否将新的DOM重新写入文件?我没有看到任何关于写入的参考,你正在引用查看xml。 - robert_x44
@RD01 - 是的,我正在将它写回到文件中。我想我现在的主要问题是,如果node.setNodeValue()既不设置文本也不设置属性,那么它是做什么的? - Grammin
4个回答

44

以下代码:

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>
希望这能澄清问题。

啊,这样就清楚了,那么node.setNodeValue()是做什么的呢? - Grammin
10
setNodeValue 方法的行为因节点类型而异(请查看Java文档中的表格:http://download.oracle.com/javase/6/docs/api/org/w3c/dom/Node.html)。如果该节点是一个 Element,则设置 nodeValue 不会有任何效果,因为 nodeValuenull - dogbane

2

为了澄清,在创建节点时,请使用以下内容:

Attr x = doc.createAttribute(...);
Comment x = doc.createComment(...);
Element x = doc.createElement(...);   // as @dogbane pointed out
Text x = doc.createTextNode(...);

使用特定的节点代替从每个方法中获取的通用节点,这将使您的代码更易于阅读/调试。

其次,getNodeValue() / setNodeValue() 方法根据您拥有的节点类型而有所不同。请参见 Node 类的摘要以供参考。对于元素,您不能使用这些方法,但对于文本节点,您可以使用它们。

正如@dogbane所指出的那样,对于此元素标记之间的文本,请使用setTextContent()。请注意,这将破坏任何现有的子元素。


2
这是另一种解决方案,在我的情况下,这个解决方案可行,因为setTextContent()函数不存在。 我正在使用Google Web Toolkit (GWT)(它是一个Java开发框架)并导入了XMLParser库,以便我可以使用DOM解析器。
引用: 导入com.google.gwt.xml.client.XMLParser; Document doc = XMLParser.createDocument(); Element node = doc.createElement("New_Node"); node.appendChild(doc.createTextNode("value")); doc.appendChild(node);
结果为: value

0

我知道在那个实例中value是一个属性,但我不知道当我设置NodeValue时value是什么,以及为什么我尝试的代码不起作用。 - Grammin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接