Wednesday, August 22, 2007

Working with Online xml

Some times we required to access the xml files which are present at online or working with another site it is required to access the data through the xml.This artical deals how to work with online xml file.The below sample code parse the xml file throuth the given URL String and returns the DOM Document.Then we can access the xml file using that document.

Code:

import java.io.InputStream;
import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class DOMProvider{
public Document getDocument(String strUrl)throws Exception{
URL url=new URL(strUrl);
InputStream in=url.openStream();
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
DocumentBuilder builder=factory.newDocumentBuilder();
Document document=builder.parse(in);
return document;
}
}

After getiing the document from getDocument() if you want to get retrive entire node list that can be done by
NodeList nodeList=document.getElementsByTagName("NameofTheNode");

By these all the node will come in that Node List.If you want to retrive the attributes with in that Node,that can be done by
Node node= nodeList.item(indx);
NamedNodeMap attrs=node.getAttributes();
String value=nnm.getNamedItem("AttributeNamewithinthatNode").getNodeValue();

Sample Work:

http://www.w3schools.com/xml/note.xml is in the form of










to work with the above xml as:


Code:

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

public class Test{
public static void main(String[] args)throws Exception{
DOMProvider test=new DOMProvider();
Document doc=test.getDocument("http://www.w3schools.com/xml/note.xml");
Node node=doc.getDocumentElement();
System.out.println("Root Node: "+node.getNodeName());
NodeList list=node.getChildNodes();
int childsLen=list.getLength();
for(int index=0;index
Node tag=list.item(index);
if(tag.getNodeType()==Node.ELEMENT_NODE){
NodeList val=tag.getChildNodes();
int vallen=val.getLength();
System.out.println("Tag Name: "+tag.getNodeName());
for(int i=0;i
if(val.item(i)!=null)
System.out.println("Tag Value: "+val.item(i).getNodeValue());
}
System.out.println();
}
}
}

}

OutPut:

Root Node: note

Tag Name: to
Tag Value: Tove

Tag Name: from
Tag Value: Jani

Tag Name: heading
Tag Value: Reminder

Tag Name: body
Tag Value: Don't forget me this weekend!

No comments: