2. SOAP


Use JAXP to get information from an XML-File


<?xml version="1.0" encoding="UTF-8"?>

<people>
 <person>
  <firstname>Fred</firstname>
  <lastname>Feuerstein</lastname>
  <age>40</age>
  <wife>Wilma</wife>
  <friend>Barney</friend>
 </person>
 <person>
  <firstname>Barney</firstname>
  <lastname>Geroellheimer</lastname>
  <age>35</age>
  <wife>Betty</wife>
  <friend>Fred</friend>
 </person>
</people>



package flintstones;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class ParseExample {
public static void main(String[] args) throws Exception {readXMLFile();printXMLDocContent();}

private final static String xmlFilePath="people.xml";

private static String xmlDocContent="";

private static void readXMLFile() throws Exception{
  
  
  DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
  DocumentBuilder builder= factory.newDocumentBuilder();
  Document doc=builder.parse(xmlFilePath);
  
  NodeList peopleList=doc.getElementsByTagName("person");
  
  
  for(int i=0;i<peopleList.getLength();i++){
   Node n_people=peopleList.item(i);
   
   if(n_people.getNodeType()==Node.ELEMENT_NODE){
    Element person=(Element)n_people;
    NodeList personList=person.getChildNodes();
    
    for(int j=0;j<personList.getLength();j++){
     Node n_person=personList.item(j);
     
     if(n_person.getNodeType()==Node.ELEMENT_NODE){
      Element e=(Element)n_person;
      xmlDocContent=xmlDocContent.concat(e.getTagName()+": "+e.getTextContent()+"\n");
     }
    }
   }
   
    
    
   xmlDocContent=xmlDocContent.concat("\n\n");
   
  }
  
  
 }

private static void printXMLDocContent(){
  System.out.println(xmlDocContent);
 }

}



Output:

firstname: Fred
lastname: Feuerstein
age: 40
wife: Wilma
friend: Barney


firstname: Barney
lastname: Geroellheimer
age: 35
wife: Betty
friend: Fred