如何在Java 1.4中向XML节点添加属性

joe*_*joe 7 java xml

我试过了:

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");
Run Code Online (Sandbox Code Playgroud)

但是这会在将其强制转换为Element的行上抛出java.lang.ClassCastException错误. mapNode是一个有效的节点. 我已经将它打印出来了

我想这个代码可能在Java 1.4中不起作用.我真正需要的是使用Element的替代方案.我试过了

NamedNodeMap atts = mapNode.getAttributes();
    Attr att = doc.createAttribute("objId");
    att.setValue(docId);    
    atts.setNamedItem(att);
Run Code Online (Sandbox Code Playgroud)

但是getAttributes()在服务器上返回null.即使它不是,我在本地使用与服务器上相同的文档.它可以打印出getNodeName(),只是getAttributes()不起作用.

joe*_*joe 1

我在服务器上使用了不同的 dtd 文件。这就是导致问题的原因。