Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get child nodes with ELEMENT_NODE type only

Tags:

java

dom

xml

I'm parsing a xml document using java DOM and I need to get every single node for doing something.

I have this code:

public void analyze_file(Node node){
        if(node.getNodeType() != Node.DOCUMENT_NODE){
            //do something
        }
        NodeList list = node.getChildNodes();
        for(int i=0; i<list.getLength(); i++){
            if(list.item(i).getNodeType() == Node.ELEMENT_NODE){
                analyze_file(list.item(i));
            }
        }
}

The problem is that, my xml file is very large ( > 30000 lines), and the code above needs too much time for checking whether a node is of ELEMENT_NODE type or not. I see that if the program stopped after it reached the last ELEMENT_NODE node, the execution time would be very small.

Is there any way to get all child nodes whose type is ELEMENT_NODE only?

For example: NodeList list = node.getElementChildNodes();

Thanks for any help!

like image 434
chuonghd Avatar asked Nov 20 '13 07:11

chuonghd


People also ask

How do you get all child nodes?

To get all child nodes, including non-element nodes like text and comment nodes, use Node. childNodes .

Which DOM node type may not have the EntityReference node type as one of its child nodes?

A CDATASection node cannot have any child nodes. The CDATASection node can appear as the child of the DocumentFragment, EntityReference, and Element nodes. The node represents a reference to an entity in the XML document (its nodeTypeString property is "entityreference").

Which interface objects Cannot have child nodes in Python?

Comment Objects Comment represents a comment in the XML document. It is a subclass of Node , but cannot have child nodes.

Which of the following properties returns a collection of a node's child nodes as a NodeList?

The HTML DOM childNodes property returns a collection of node's child nodes in the form of a NodeList object.


1 Answers

node.getElementsByTagName("*")

From JavaDoc: Returns a NodeList of all descendant Elements with a given tag name, in document order. Name - The name of the tag to match on. The special value "*" matches all tags.

like image 134
pasha701 Avatar answered Sep 30 '22 20:09

pasha701