Java DOM: add an attribute to a node

A

Ale

Hi all,

I need to write a new XML file from scratch, I've just a doubt about
adding an attribute to an element.

This is the code, but maybe there is a way to write less code to do
that.
What do you think about that ?

//START CODE
....
Document doc=docBuilder.newDocument();

Node rootNode=doc.createElement("MarketNews");
Attr id=doc.createAttribute("id");
id.setValue("123456");
NamedNodeMap rootAttr=rootNode.getAttributes();
rootAttr.setNamedItem(id);

doc.appendChild(rootNode);
....
//END CODE


Thanks all and best regards,
Ale
 
A

Arne Vajhøj

I need to write a new XML file from scratch, I've just a doubt about
adding an attribute to an element.

This is the code, but maybe there is a way to write less code to do
that.
What do you think about that ?
Node rootNode=doc.createElement("MarketNews");
Attr id=doc.createAttribute("id");
id.setValue("123456");
NamedNodeMap rootAttr=rootNode.getAttributes();
rootAttr.setNamedItem(id);

Try:

Node rootNode=doc.createElement("MarketNews");
Attr id=doc.createAttribute("id");
id.setValue("123456");
rootNode.setAttributeNode(id);

Arne
 
M

Mike Schilling

Arne said:
Try:

Node rootNode=doc.createElement("MarketNews");
Attr id=doc.createAttribute("id");
id.setValue("123456");
rootNode.setAttributeNode(id);

Or, more simply

Element root = doc.createElement("MarketNews");
doc.appendChild(root);
root.setAttribute("id", "123456");
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top