Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

W3C DOM API in Java, get child elements by name

Tags:

I just realized that the method Element.getElementsByTagName("someTagName") returns a nodelist of all elements in the document that have a given tagname. What if I just want to get all child elements by tag name?

For example...

<person>   <name>Bob</name>   <car>     <name>Toyota Corolla</name>   </car> </person> 
like image 444
benstpierre Avatar asked Apr 14 '10 19:04

benstpierre


2 Answers

public static Element getDirectChild(Element parent, String name) {     for(Node child = parent.getFirstChild(); child != null; child = child.getNextSibling())     {         if(child instanceof Element && name.equals(child.getNodeName())) return (Element) child;     }     return null; } 
like image 195
Eng.Fouad Avatar answered Sep 23 '22 00:09

Eng.Fouad


Had the same problem but none of the answers actually solved the question.

I was trying to query the operation Nodes INSIDE the portType Node of a WSDL, given that the binding node also have operations.

<portType name="MyService">     <operation name="op1">       <input wsam:Action="http://somedomain.org/MyService/MyServiceRequest" message="tns:MyServiceRequest"/>       <output wsam:Action="http://somedomain.org/MyService/MyServiceResponse" message="tns:MyServiceResponse"/>     </operation>     ... </portType> <binding name="MyServicePortBinding" type="tns:MyService">     <soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="document"/>     <operation name="op1">       <soap:operation soapAction=""/>       <input>         <soap:body use="literal"/>       </input>       <output>         <soap:body use="literal"/>       </output>     </operation> </binding> 

Solved it by finding the parent (portTypes) and just casting it from Node to Element and using the method named above.

Node portType = document.getElementsByTagName("portType").item(0); NodeList operations = ((Element)portType).getElementsByTagName("operation"); 

Which gave me as a result the operation elements INSIDE portType Node only.

like image 29
Ulises Layera Avatar answered Sep 26 '22 00:09

Ulises Layera