屬性添加到XML節點我想:如何在Java 1.4
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");
但是,這將引發java.lang.ClassCastException錯誤的,它造型爲元素的行。 mapNode是一個有效的節點。我已經打印出來了
我想也許這個代碼在Java 1.4中不起作用。我真正需要的是使用Element的替代方案。我試過
NamedNodeMap atts = mapNode.getAttributes();
Attr att = doc.createAttribute("objId");
att.setValue(docId);
atts.setNamedItem(att);
但是getAttributes()在服務器上返回null。即使它不是,我在本地使用與服務器上相同的文檔。它可以打印出getNodeName()它的getAttributes()不起作用。
你能提供更多的細節嗎?什麼是確切的堆棧跟蹤? – gizmo 2008-09-30 18:12:45
堆棧跟蹤說的唯一有用的信息是java.lang.ClassCastException – joe 2008-09-30 18:16:45
在Element e =(Element)doc.getFirstChild()行拋出它 – joe 2008-09-30 18:17:18