Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

xml

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.

like image 848
joe Avatar asked Sep 30 '08 18:09

joe


People also ask

How do you add an element to an attribute in XML?

Get the element node and use SetAttribute to add an attribute to the attribute collection of that element. Create an XmlAttribute node using the CreateAttribute method, get the element node, then use SetAttributeNode to add the node to the attribute collection of that element.

What is attribute node in XML?

According to the XML DOM, everything in an XML document is a node: The entire document is a document node. Every XML element is an element node. The text in the XML elements are text nodes. Every attribute is an attribute node.


1 Answers

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

like image 188
joe Avatar answered Oct 05 '22 23:10

joe