wood burning stoves 2.0*
The moose likes XML and Related Technologies and the fly likes adding more attributes+DOM Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Engineering » XML and Related Technologies
Bookmark "adding more attributes+DOM" Watch "adding more attributes+DOM" New topic
Author

adding more attributes+DOM

Maggie Taylor
Greenhorn

Joined: Feb 14, 2006
Posts: 10
Here's an xml file
<COURSE>
<exam date="13-feb-2006" type="v">
.....
</exam>
<STUDENT id="studid">

</STUDENT>
...�..
</COURSE>

I would like to add attribute firstname to STUDENT element(using DOM) so that it shows information like this
<COURSE>
<exam date="13-feb-2006" type="v">
.....
</exam>
<STUDENT id="id" firstname="maggie" >

</STUDENT>
...�..
</COURSE>

I tried running this code

But I get this error, when I run the program

java.lang.NullPointerException
at DOMAdd.main(DOMAdd.java:49)

Is there something wrong with the coding?

-M
[ February 21, 2006: Message edited by: Maggie Taylor ]
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18662
    
    8

If you get a NullPointerException then by definition there's an error in the coding.

In your case, after this line of codeis executed, the "element" variable is null. That's because you made the common mistake of assuming that the getElementById() method looks for elements that have an attribute whose name is "id". It doesn't. It looks for elements that have an attribute that is defined, by a DTD or a schema, to be an "ID" attribute.

But you don't have anything that describes the document content like that. So you will have to write code that looks at all the <STUDENT> elements and adds an attribute to the right ones. The getElementsByTagName() method will help here. And by the way, the line of codeis unnecessary (and possibly harmful). The element is already part of the document and looking at it doesn't change that.
Maggie Taylor
Greenhorn

Joined: Feb 14, 2006
Posts: 10
Originally posted by Paul Clapham:


In your case, after this line of code Element element = doc.getElementById("studid"); is executed, the "element" variable is null. That's because you made the common mistake of assuming that the getElementById() method looks for elements that have an attribute whose name is "id". It doesn't. It looks for elements that have an attribute that is defined, by a DTD or a schema, to be an "ID" attribute.


Thanx Paul, I learnt something new. I added the attribute "id" to the DTD, and then used the code. And it works fine.

-M
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: adding more attributes+DOM