xml dom parser in java? [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 8 years ago.
Improve this question
can any one share good document for dom parser in java.
thanks

Following are tutorial for using DOM in java:
xml dom
DOM-Parser
java-xml-dom
dom example
Hope this helps.

Check this Simple Parser XML with DOM Example and this Sax Example:
public class ReadXMLFile {
public static void main(String argv[]) {
try {
File fXmlFile = new File("/Users/mkyong/staff.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
//optional, but recommended
//read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("staff");
System.out.println("----------------------------");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
System.out.println("\nCurrent Element :" + nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
System.out.println("Staff id : " + eElement.getAttribute("id"));
System.out.println("First Name : " + eElement.getElementsByTagName("firstname").item(0).getTextContent());
System.out.println("Last Name : " + eElement.getElementsByTagName("lastname").item(0).getTextContent());
System.out.println("Nick Name : " + eElement.getElementsByTagName("nickname").item(0).getTextContent());
System.out.println("Salary : " + eElement.getElementsByTagName("salary").item(0).getTextContent());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

Related

Get element with xml dom parser [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
How to get restaurant name in jbeil only using xml DOM parser , please help :
And this is my XML file
<city>
<beirut>
<restaurant>
<name>sada</name>
</restaurant>
</beirut>
<jbeil>
<restaurant>
<name>sada</name>
</restaurant>
</jbeil>
<sour>
<restaurant>
<name>sada</name>
</restaurant>
</sour>
</city>
I want to get the name of restaurant in Jbeil using dom parser and this code give me restaurants name in all city's:
try {
File inputFile = new File("src/josephXml.xml");
DocumentBuilderFactory dbFactory
= DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(inputFile);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("Restaurant");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
jTextArea1.append( "\n"+"Name : "+ eElement
.getElementsByTagName("name")
.item(0)
.getTextContent()+"\n "
use XPath
many resources: http://viralpatel.net/blogs/java-xml-xpath-tutorial-parse-xml/
something like that (not tested)
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;
XPath xPath =  XPathFactory.newInstance().newXPath();
String expression = "/city/jbeil/restaurant/name";
//read a string value
String thename= xPath.compile(expression).evaluate(xmlDocument);
Using the same code style as you and "only using xml DOM parser" get the jbeil and then the restaurant...
NodeList nList = doc.getElementsByTagName("jbeil");
for (int i = 0; i < nList.getLength(); i++) {
Node nNode = nList.item(i);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
NodeList nList2 = eElement.getElementsByTagName("restaurant");
for (int n = 0; n < nList.getLength(); n++) {
Node nNode2 = nList2.item(n);
if (nNode2.getNodeType() == Node.ELEMENT_NODE) {
Element eElement2 = (Element) nNode;
System.out.println(eElement2.getElementsByTagName("name").item(0).getTextContent());
}
}
}
}
But I would go for the XPath answer...

update xml document using xpath

Hello this is my xml document :
<city>
<beirut>
<restaurant>
<name>sada</name>
</restaurant>
</beirut>
<jbeil>
<restaurant>
<name>toto</name>
<rating>4.3/5</rating>
</restaurant>
<restaurant>
<name>jojo</name>
<rating>4.3/5</rating>
</restaurant>
</jbeil>
<sour>
<restaurant>
<name>sada</name>
</restaurant>
</sour>
</city>
I want to update the rating of "jojo" restaurant in jbeil from 4.3/5 to 4.5/5 using xpath and netbeans please help ,
this code give the rating ,
try {
File inputFile = new File("src/xpath/josephXml.xml");
DocumentBuilderFactory dbFactory
= DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder;
dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(inputFile);
doc.getDocumentElement().normalize();
XPath xPath = XPathFactory.newInstance().newXPath();
String expression = "/City/Jbeil/Restaurant";
NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(doc, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
Node nNode = nodeList.item(i);
System.out.println("\nCurrent Element :"
+ nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
System.out.println("rating : "
+ eElement
.getElementsByTagName("rating")
.item(0)
.getTextContent());
and i want only to update the rating of restaurant in jbeil where name is "jojo" , please help
This is one possible XPath to find such restaurant named jojo in the city of jbeil and then return the corresponding rating element :
/city/jbeil/restaurant[name='jojo']/rating
Notice that XML & XPath are case-sensitive, so I used all lower-case characters in the above XPath to match the XML posted in this question.
I don't know much about Java, but quick searching over the internet* suggest something like this :
XPath xpath = XPathFactory.newInstance().newXPath();
String expression = "/city/jbeil/restaurant[name='jojo']/rating";
Element e = (Element)xpath.evaluate(expression, doc, XPathConstant.NODE);
if (e != null)
e.setTextContent("4.5/5");
*) how to modify xml tag specific value in java?

reading data using JAVA from XML files

I know there was a lot of answers about this question but all didn't work in my case. I would read data from European Central Bank from this link ECB. For example, how to read "rate" of USD where time="2015-02-27" and how to read "rate" of USD from all 90 days ?
One of the simplest ways to do it is to use a DOM (Document Object Model) parser. It will load your xml document in memory and turns it into a tree made of Nodes so that you can travers it being able to get the information of any node at any position. It is memory consumming and is generally less prefered than a SAX parser.
Here is an example:
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;
public class DomParsing {
public static final String ECB_DATAS ="C:\\xml\\eurofxref-hist-90d.xml";
public static void main(String argv[]) {
try {
File fXmlFile = new File(ECB_DATAS);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("Cube");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
System.out.println("\nCurrent Element :" + nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
System.out.println("currency : " + eElement.getAttribute("currency") + " and rate is " + eElement.getAttribute("rate"));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Applied to your file produces the following result:
currency : BGN and rate is 1.9558
Current Element :Cube
currency : CZK and rate is 27.797
Current Element :Cube
currency : DKK and rate is 7.444

traversing DOM parsed XML [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Traversing complex xml File in android
In this i am parsing an xml file using DOM parser which is giving me dom1 as the parsed document.
the problem is that i want to create UI after this,and i am unable to the same as i can't find a logic to the same please help me with that.Also this is giving me wrong getLength() values. What is wrong with it??
the xml is in this link:
http://nchc.dl.sourceforge.net/project/trialxml/options.xml
//this is function is called when i click my button
public void next123(View view){
Element root=dom1.getDocumentElement();
NodeList nodes=root.getChildNodes();
create_Menu(nodes);
}
public void create_Menu(NodeList nodes){
for(int i=0;i<nodes.getLength();i++){
Node node=nodes.item(i);
if(node instanceof Element){
Element child = (Element)node;
String name=getTextValue(child,"Name");
String typ=child.getAttribute("type");
if(name!=null){
z++;
Log.i(TAG,"Names are:= " +name+ " -> "+typ +" -> "+ z+ " -> "+ i);
NodeList nod=child.getChildNodes();
Log.i(TAG,"Length : "+nod.getLength());
create_Menu(nod);
Log.i(TAG,"end");
}
}
}
}
i have to create a UI after this, for that i am using ListView and an array of ArrayList to store my values. the problem is i have to assign a no. to every level,
for example if my array is test[], then
test[0]-> main,
test[1]->1L1,1L2,1L3,
test[2]->2L1,
test[3]->2L2
test[4]->3L1,3L2
please the xml for refrence.
I am just giving an example, try to do it this way....
DocumentBuilderFactory odbf = DocumentBuilderFactory.newInstance();
DocumentBuilder odb = odbf.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(xml));
Document odoc = odb.parse(is);
odoc.getDocumentElement().normalize (); // normalize text representation
System.out.println ("Root element of the doc is " + odoc.getDocumentElement().getNodeName());
NodeList LOP = odoc.getElementsByTagName("locations");
int totalPersons =LOP.getLength();
System.out.println("Total nos of locations:"+totalPersons);
for(int s=0; s<LOP.getLength() ; s++)
{
Node FPN =LOP.item(s);
if(FPN.getNodeType() == Node.ELEMENT_NODE)
{
Element latlon = (Element)FPN;
NodeList oNameList1 = latlon.getElementsByTagName("featured");
Element firstNameElement = (Element)oNameList1.item(0);
NodeList textNList1 = firstNameElement.getChildNodes();
featuredArr = changeToBoolean(((Node)textNList1.item(0)).getNodeValue().trim()); // value taken
System.out.println("#####The Parsed data#####");
System.out.println("featured : " + ((Node)textNList1.item(0)).getNodeValue().trim());
System.out.println("#####The Parsed data#####");
}
}

java xml dom parsing

I have this project I'm working on where I want to parse an xml file that looks like this:
<?xml version='1.0' encoding='UTF-8'?>
<projectlist>
<project>
<name>SuperDuperApp</name>
<type>batch</type>
<prod>
<server>testserver01</server>
</prod>
<qa>
<server>testserver01</server>
</qa>
<dev>
<server>testserver01</server>
</dev>
</project>
<project>
<name>Calculator</name>
<type>deploy</type>
<prod>
<server>testserver02</server>
<server>testserver03</server>
<server>testserver04</server>
</prod>
<qa>
<server>testserver05</server>
<server>testserver06</server>
<server>testserver07</server>
</qa>
<dev>
<server>testserver12</server>
<server>testserver13</server>
<server>testserver14</server>
</dev>
</project>
</projectlist>
With this method parsing the file and trying to print out in the format:
name: SuperDuperApp
type: batch
server: testserver01
name: Calculator
type: deploy
environment: dev
server: testserver12
server: testserver13
server: testserver14
etc.
public void parseXML() {
ArrayList al = new ArrayList();
HashSet hs = new HashSet();
try {
InputStream file = this.getClass().getResourceAsStream(
"/net/swing/sandbox/util/config/projectlist.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(file);
doc.getDocumentElement().normalize();
System.out.println("Root element: " + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("project");
System.out.println("Information of all servers...");
for (int i=0;i<nList.getLength();i++){
Node fstNode = nList.item(i);
if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
Element fstElement = (Element) fstNode;
NodeList nameElementList = fstElement.getElementsByTagName("name");
Element nameElement = (Element) nameElementList.item(0);
NodeList name = nameElement.getChildNodes();
System.out.println("project name: " + ((Node) name.item(0)).getNodeValue());
hs.add(((Node) name.item(0)).getNodeValue());
NodeList typeElementList = fstElement.getElementsByTagName("type");
Element typeElement = (Element) typeElementList.item(0);
NodeList type = typeElement.getChildNodes();
System.out.println("Deploy type: " + ((Node) type.item(0)).getNodeValue());
//print out server list can't do it for some reason
}
}
} catch (Exception e) {
e.printStackTrace();
}
try {
al.clear();
al.addAll(hs);
Collections.sort(al);
for (int z = 0; z < al.size(); z++) {
listModel.addElement(al.get(z));
}
} catch (Exception e) {
e.printStackTrace();
}
lstProject.validate();
}
So I rewrote my method and now I'm just stuck <---newb
Check the documentation for Node. Each node has a method getChildNodes. Check that for the existence of children nodes and than iterate over them like you are doing.
If your xml was created using an xsd schema, you could instead use JAXB to create classes for it, using the xjc tool. That should make your life a bit easier.
I think it's appropriate to use XSLT transform in your case (much less boilerplate code) Look at TransformerFactory and java api for xml processing.
As a q&d solution you could apply the same strategy as for getting "project" node:
...
System.out.println("servers:");
NodeList sList = eElement.getElementsByTagName("server");
for (int i = 0; i < sList.getLength(); i++) {
String stuff = sList.item(i).getFirstChild().getNodeValue();
System.out.println(stuff);
}

Categories