-->

Problems setting a new node value in java, dom, xm

2020-06-08 03:23发布

问题:

I have the following code:

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

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" />

or does it put value here:

<New_Node> New_Node_value </New_Node>

Any help would be greatly appreciated,

Thanks, Josh

回答1:

The following code:

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

produces:

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

Hope this clarifies.



回答2:

For clarification, when you create nodes use:

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

instead of using the generic Node for what you get back from each method. It will make your code easier to read/debug.

Secondly, the getNodeValue() / setNodeValue() methods work differently depending on what type of Node you have. See the summary of the Node class for reference. For an Element, you can't use these methods, although for a Text node you can.

As @dogbane pointed out, use setTextContent() for the text between this element's tags. Note that this will destroy any existing child elements.



回答3:

This is other solution, in my case this solution is working because the setTextContent() function not exist. I am working with Google Web Toolkit (GWT) (It is a development framework Java) and I am imported the XMLParser library for I can use DOM Parser.

import com.google.gwt.xml.client.XMLParser;

Document doc = XMLParser.createDocument();

Element node = doc.createElement("New_Node"); node.appendChild(doc.createTextNode("value"));

doc.appendChild(node);

The result is:

<New_Node> value </New_Node>



回答4:

<New_Node value="New_Node_value" />

'value' is an attribute of

New_Node

element, for getting into DOM I suggest you http://www.w3schools.com/htmldom/default.asp



标签: java xml dom