Java – How to add an attribute to an XML node in Java 1.4

javaxml

I tried:

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(f);
Node mapNode = getMapNode(doc);
System.out.print("\r\n elementName "+ mapNode.getNodeName());//This works fine.

Element e = (Element) mapNode; //This is where the error occurs
//it seems to work on my machine, but not on the server.
e.setAttribute("objectId", "OBJ123");

But this throws a java.lang.ClassCastException error on the line that casts it to Element. mapNode is a valid node. I already have it printing out

I think maybe this code does not work in Java 1.4. What I really need is an alternative to using Element. I tried doing

NamedNodeMap atts = mapNode.getAttributes();
    Attr att = doc.createAttribute("objId");
    att.setValue(docId);    
    atts.setNamedItem(att);

But getAttributes() returns null on the server. Even though its not and I am using the same document locally as on the server. And it can print out the getNodeName() its just that the getAttributes() does not work.

Best Solution

I was using a different dtd file on the server. That was causing the issue.