2008-09-30 42 views
7

屬性添加到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()不起作用。

+0

你能提供更多的細節嗎?什麼是確切的堆棧跟蹤? – gizmo 2008-09-30 18:12:45

+0

堆棧跟蹤說的唯一有用的信息是java.lang.ClassCastException – joe 2008-09-30 18:16:45

+0

在Element e =(Element)doc.getFirstChild()行拋出它 – joe 2008-09-30 18:17:18

回答

1

我在服務器上使用了不同的dtd文件。這是造成這個問題。

0

可能第一個孩子只是一個空白文本節點或類似?

嘗試:

System.out.println(doc.getFirstChild().getClass().getName()); 

編輯:

只是看着它在我自己的代碼,你需要:

doc.getDocumentElement().getChildNodes(); 

或者:

NodeList nodes = doc.getElementsByTagName("MyTag"); 
0

我想你強制轉換doc.getFirst的輸出Child()是你得到異常的地方 - 你得到了一些非Element節點對象。堆棧跟蹤上的行號是否指向該行?您可能需要執行doc.getChildNodes()並遍歷來查找第一個Element子元素(doc根),從而跳過非元素節點。

您的e.setAttribute()調用看起來很明智。假設e是一個元素,並且您實際上到達該行...

0

如前所述,ClassCastException可能不會被引入setAttribute。檢查堆棧中的行號。我的猜測是getFirstChild()返回DocumentType,而不是Element

試試這個:

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 

DocumentBuilder db = dbf.newDocumentBuilder(); 
Document doc = db.parse(f); 

Element e = (Element) doc.getDocumentElement().getFirstChild(); 
e.setAttribute("objectId", "OBJ123"); 

更新:

好像你是在混淆NodeElementElementNode的實現,但當然不是唯一的一個。所以,並不是所有的Node都可澆注到Element。如果演員在一臺機器上工作而不在另一臺機器上工作,那是因爲你從getMapNode()得到了其他的東西,因爲解析器的行爲不同。 XML解析器在Java 1.4中是可插入的,因此您可以從不同的供應商那裏得到完全不同的實現,甚至具有不同的錯誤。

由於您沒有發帖getMapNode()我們看不到它在做什麼,但是您應該清楚您希望返回哪個節點(使用getElementsByTagName或其他)。