【发布时间】:2008-09-30 18:07:59
【问题描述】:
我试过了:
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");
但这会在将其转换为 Element 的行上引发 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() 不起作用。
【问题讨论】:
-
您能否提供更多详细信息?确切的堆栈跟踪是什么?
-
堆栈跟踪显示的唯一有用信息是 java.lang.ClassCastException
-
将它扔到 Element e = (Element) doc.getFirstChild() 行
-
mapNode.getClass().getName() 报告什么?如果它不是一个元素,那么了解它的真正含义将帮助您解决问题。
-
成为有效节点并不意味着它是一个元素。 'getNodeName' 在两台机器上打印什么?