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

时间:2020-03-06 14:56:16  来源:igfitidea点击:

我试过了:

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()不起作用。

解决方案

第一个孩子可能是只有空格的文本节点吗?

尝试:

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

编辑:

只需在我自己的代码中查找它,我们需要:

doc.getDocumentElement().getChildNodes();

或者:

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

我认为我们对doc.getFirstChild()输出的转换是我们遇到异常的地方-我们正在获取一些非Element Node对象。堆栈跟踪中的行号是否指向该行?我们可能需要执行doc.getChildNodes()并进行迭代以查找第一个Element子节点(文档根目录),从而跳过非Element节点。

e.setAttribute()调用看起来很明智。假设e是一个Element,并且我们实际上到达那一行...

如前所述,可能不会在setAttribute中引发ClassCastException。检查堆栈中的行号。我的猜测是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");

更新:

看来我们混淆了Node和Element。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。 Element是Node的实现,但当然不是唯一的。因此,并非所有的Node都可以转换为Element。如果强制转换是在一台机器上而不是另一台机器上工作,那是因为我们从getMapNode()中获得了其他东西,因为解析器的行为方式有所不同。 XML解析器可插入Java 1.4中,因此我们可能会从不同的供应商那里获得完全不同的实现,甚至会有不同的错误。

由于我们没有发布getMapNode(),所以我们看不到它在做什么,但是我们应该明确要返回的节点(使用getElementsByTagName或者其他方式)。

我在服务器上使用了其他dtd文件。那就是问题所在。