Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems setting a new node value in java, dom, xml parsing

Tags:

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

like image 664
Grammin Avatar asked Jan 13 '11 14:01

Grammin


People also ask

How does a DOM parser load XML?

Constructs a DOM tree by parsing a string containing XML, returning a XMLDocument or Document as appropriate based on the input data. Loads content from a URL; XML content is returned as an XML Document object with a DOM tree built from the XML itself.


1 Answers

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.

like image 93
dogbane Avatar answered Dec 14 '22 22:12

dogbane