Java DOM getElementByID

前端 未结 2 566
轻奢々
轻奢々 2021-01-07 08:07

I am using DOM parser in Java to add child nodes into existing nodes.

My XML is


          


        
相关标签:
2条回答
  • 2021-01-07 08:24

    edit: To the original Question: Yes the appendChild thing works the way you planed, the problem lies within getElementById.

    The NullPointerException means there was no Element with that ID. The javadoc gives it away:

    http://docs.oracle.com/javase/1.5.0/docs/api/org/w3c/dom/Document.html#getElementById(java.lang.String)

    The DOM implementation is expected to use the attribute Attr.isId to determine if an attribute is of type ID.

    and further in the Documentation of Attr:

    http://docs.oracle.com/javase/1.5.0/docs/api/org/w3c/dom/Attr.html#isId()

    So basically you need either a DTD or a schema for your document and need to set

    DocumentBuilderFactory.setValidating(true)
    

    or set the IsId property by hand.

    personally i used: (dirty&scala for lazyness)

    import org.w3c.dom.{Document,Node,Attr,Element}
    
    def idify ( n:Node ) {
      if ( n.getNodeType() == Node.ELEMENT_NODE ){
            val e = n.asInstanceOf[Element ]
            if (e.hasAttributeNS(null , "id" ) )e.setIdAttributeNS(null , "id" , true )
      }
      val ndlist = n.getChildNodes()
      for ( i <- 0 until ndlist.getLength ) idify(ndlist.item(i) )
    }
    

    There surely are more professional ways to do this that do not involve drafting up a complete DTD/schema. If someone knows, i'm curious as well.

    0 讨论(0)
  • 2021-01-07 08:49

    getElementById is specifically for retrieving DOM elements by their id attribute. Try this instead:

    this.widgetDoc.getElementById("legendNode").appendChild(myNode);
    

    For other ways of retrieving DOM nodes, look into querySelector and querySelectorAll.

    0 讨论(0)
提交回复
热议问题