Reading XML file online - java

I was searching code that I can use to read XML file. and I did find one as below. But my problem is, I'm unable to read a XML file online. When I give the URL of the XML file location, it returns File Not Found Exception. Can someone advice. Thanks in advance.
import java.io.File;
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 XMLReader {
public static void main(String argv[]) {
try {
File file = new File("MyXML.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(file);
doc.getDocumentElement().normalize();
System.out.println("Root element " + doc.getDocumentElement().getNodeName());
NodeList nodeLst = doc.getElementsByTagName("employee");
System.out.println("Information of all employees");
for (int s = 0; s < nodeLst.getLength(); s++) {
Node fstNode = nodeLst.item(s);
if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
Element fstElmnt = (Element) fstNode;
NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("firstname");
Element fstNmElmnt = (Element) fstNmElmntLst.item(0);
NodeList fstNm = fstNmElmnt.getChildNodes();
System.out.println("First Name : " + ((Node) fstNm.item(0)).getNodeValue());
NodeList lstNmElmntLst = fstElmnt.getElementsByTagName("lastname");
Element lstNmElmnt = (Element) lstNmElmntLst.item(0);
NodeList lstNm = lstNmElmnt.getChildNodes();
System.out.println("Last Name : " + ((Node) lstNm.item(0)).getNodeValue());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

It was discoused on stackoverflow: How to read XML response from a URL in java?

You can leverage the java.net.URL class:
URL xmlURL = new URL("http://www.cse.lk/listedcompanies/overview.htm?d-16544-e=3&6578706f7274=1");
InputStream xml = xmlURL.openStream();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(xml);
xml.close();

If you are trying to communicate with a Restful Service, you might benefit from using a library. Open source libraries with goodies in this area include Apache CXF and Jersey.

Related

read an XML file in Java application?

Read in an XML file in Java application?
doc.getDocumentElement().normalize();
I am getting an error:
"Syntax error on token "getDocumentElement", Identifier expected after this token".
here is full code:
package SalesForce_Common;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
public class ReadDataFromXmlFile {
File fXmlFile = new File("/Users/mkyong/staff.xml");
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("staff");
System.out.println("----------------------------");
}}
Syntax error means that your code isn't correct from the compiler point of view, so we need the full code snippet in order to help you.
You cannot write code directly in a Java class. You need to wrap it in a method. In your case, it seems you want a main:
public class ReadDataFromXmlFile throws IOException, SAXException, ParserConfigurationException {
public static void main (String[] args) {
File fXmlFile = new File("/Users/mkyong/staff.xml");
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("staff");
System.out.println("----------------------------");
}
}

Not able to parse inner elements of XML using DocumentBuilderFactory in Java

I'm having a response as XML. I'm trying to parse the XML object to get inner details. Im using DocumentBuilderFactory for this. The parent object is not null, but when I try to get the deepnode list elements, its returning null. Am I missing anything
Here is my response XML
ResponseXML
<DATAPACKET REQUEST-ID = "1">
<HEADER>
</HEADER>
<BODY>
<CONSUMER_PROFILE2>
<CONSUMER_DETAILS2>
<NAME>David</NAME>
<DATE_OF_BIRTH>1949-01-01T00:00:00+03:00</DATE_OF_BIRTH>
<GENDER>001</GENDER>
</CONSUMER_DETAILS2>
</CONSUMER_PROFILE2></BODY></DATAPACKET>
and Im parsing in the following way
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(responseXML));
// Consumer details.
if(doc.getDocumentElement().getElementsByTagName("CONSUMER_DETAILS2") != null) {
Node consumerDetailsNode = doc.getDocumentElement().getElementsByTagName("CONSUMER_DETAILS2").item(0); -->This is coming as null
dateOfBirth = getNamedItem(consumerDetailsNode, "DATE_OF_BIRTH");
System.out.println("DOB:"+dateOfBirth);
}
getNamedItem
private static String getNamedItem(Node searchResultNode, String param) {
return searchResultNode.getAttributes().getNamedItem(param) != null ? searchResultNode.getAttributes().getNamedItem(param).getNodeValue() : "";
}
Any ideas would be greatly appreciated.
The easiest way to search for individual elements within an XML document is with XPAth. It provides search syntax similar to file system notation.
Here is a solution to the specific problem of you document:
EDIT: solution adopted to support multiple CONSUMER_PROFILE2 elements. You just need to get and parse NodeList instread of one Node
import java.io.*;
import javax.xml.parsers.*;
import javax.xml.xpath.*;
import org.w3c.dom.*;
import org.xml.sax.*;
public class XpathDemo
{
public static void main(String[] args)
{
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document xmlDoc = builder.parse(new InputSource(new FileReader("C://Temp/xx.xml")));
// Selects all CONSUMER_PROFILE2 elements no matter where they are in the document
String cp2_nodes = "//CONSUMER_PROFILE2";
// Selects first DATE_OF_BIRTH element somewhere under current element
String dob_nodes = "//DATE_OF_BIRTH[1]";
// Selects text child node of current element
String text_node = "/child::text()";
XPath xPath = XPathFactory.newInstance().newXPath();
NodeList dob_list = (NodeList)xPath.compile(cp2_nodes + dob_nodes + text_node)
.evaluate(xmlDoc, XPathConstants.NODESET);
for (int i = 0; i < dob_list.getLength() ; i++) {
Node dob_node = dob_list.item(i);
String dob_text = dob_node.getNodeValue();
System.out.println(dob_text);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

Android XML: open failed: ENOENT (No such file or directory) , DOMParser

I have a problem to using a DOMParserXML to take data stored in a xml file called: "infofermata.xml" and placed this path: "xml/infofermata.xml".
The first problem that I found is: "2246-2246/com.example.giacomob.myapplication W/System.errīš• java.io.FileNotFoundException: /xml\infofermata.xml: open failed: ENOENT (No such file or directory)"
The class that will read in this XML file is:
package com.example.giacomob.myapplication;
import android.util.Log;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
public class ReadXMLFile {
public ReadXMLFile() {
try {
Log.i("MyActivity", "casa");
String filePath = "xml\\infofermata.xml";
File fXmlFile = new File(filePath);
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("fermata");
System.out.println("----------------------------");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
System.out.println("\nCurrent Element :" + nNode.getNodeName());
// Log.i("MyActivity", "casa");
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
// System.out.println("Staff id : " + eElement.getAttribute("id"));
// String stringidfermata = "Id Fermata : " + eElement.getElementsByTagName("idfermata").item(0).getTextContent()"";
// Log.i("MyActivity", "\"Id Fermata : \" + eElement.getElementsByTagName(\"idfermata\").item(0).getTextContent()");
System.out.println("Id Fermata : " + eElement.getElementsByTagName("idfermata").item(0).getTextContent());
System.out.println("Naziome : " + eElement.getElementsByTagName("nazione").item(0).getTextContent());
System.out.println("Paese : " + eElement.getElementsByTagName("paese").item(0).getTextContent());
System.out.println("Via : " + eElement.getElementsByTagName("via").item(0).getTextContent());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
I supposed that the error is in: " String filePath = "xml\infofermata.xml";", ma that path aren't wrong...please, help me!!
This is my XML file:
<?xml version="1.0" encoding="utf-8"?>
<fermata>
<idfermata>1</idfermata>
<nazione>Italia</nazione>
<paese>Lecce</paese>
<via>Viale Grassi</via>
</fermata>
Thanks :)
Giacomo, the res folder is reserved for application resources, then to read a file in it you have to use the getResources() method, and then the getXml(). This example is a little bit outdated, but I believe can help you.If you want to use the DocumentBuilderFactory and the other java class for DOM, I suggest you to put your xml in the 'assets' folder of your app, the you get the InputStream using:
AssetManager assetManager = getAssets();
InputStream is = assetManager.open("infofermata.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(is);
[...]
is.close();
Hope it can help.

Why am I getting a DefferedDocumentImpl when trying to create a JDOM Document?

Im trying to parse the input stream from a zipfile zip entry and trying to create a org.w3c.dom.Document but for some reason im getting a DefferedDocumentImpl back. Im also creating a new org.w3c.dom.Document and this is returning a DocumentImpl. Then using Xpath to select a single node but im getting this error "org.apache.xerces.dom.DocumentImpl incompatible with org.jdom.Element" when Im trying to find my specific node. Ive done some searching but cant seem to find and examples. Anyone know why im not getting my docs created as dom docs? Thanks in advance for the help.
//create a zip file from the crate location
File downloadFile = crate.getLocation();
ZipFile zipFile = new ZipFile(downloadFile);
//put all the contents of the zip file into an enumeration
Enumeration entries = zipFile.entries();
while (entries.hasMoreElements()){
ZipEntry entry = (ZipEntry) entries.nextElement();
String currentEntry = entry.getName();
if (currentEntry.equals("ATTACH 8130-3 XML/signature.xml")){
InputStream zipStream = zipFile.getInputStream(entry);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
org.w3c.dom.Document doc = (org.w3c.dom.Document)dBuilder.parse(zipStream);
doc.getDocumentElement().normalize();
NodeList certNode = doc.getElementsByTagName("ATA_PartCertificationForm");
int testInt = certNode.getLength();
org.w3c.dom.Document doc2 = (org.w3c.dom.Document) dBuilder.newDocument();
Node parentNode = doc.getParentNode();
Element rootElement = doc2.createElement("CurrentCertificate");
doc2.appendChild(rootElement);
for(int i=0; i<certNode.getLength(); i++){
Node childNode = certNode.item(i);
Element childElement;
childElement = (Element)certNode.item(i);
rootElement.appendChild(doc2.importNode(childNode, true));
String nameString = childNode.getNodeName();
Element block13Element = (Element) XPath.selectSingleNode(doc2, "//Block13M");
System.out.println("tester test");
}
System.out.println("Test break");
}
}
You're passing an org.w3c.dom.Document to jdom.xpath.XPath.selectSingleNode(), but that method expects an org.jdom.Document or an org.jdom.Element.
Here's one way to parse your XML as a JDOM document and execute an XPath query using Jaxen, which must also be in the classpath.
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.xpath.XPath;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class JdomXpathSandbox {
public static void main(String[] args) throws Exception {
InputStream is = ...;
Document document = new SAXBuilder().build(is);
Element rootElement = document.getRootElement();
String xpathExpression = ...
List matchingNodes = XPath.selectNodes(rootElement, xpathExpression);
}
}

Reading XML as string in Java

Could somebody help me with this. I would like to know how to read this example as string? I know how to read first one but don't know how to read them all
<Tr rn=\"000000000000000\" vr=\"T\" sSpre=\"S\" reg=\"P\" dSpre=\"2000-01-01\" dOdprt=\"2000-01-01\" iban=\"SI00\" eno=\"R\" vir=\"B\" maticnaPps=\"0000000000\"><Imetnik davcna=\"00000000\" matSub=\"0000000000\" drz=\"705\"><PopolnoIme>UNKNOWN</PopolnoIme><KratkoIme>UNKNOWN</KratkoIme><Naslov sifTipNaslova=\"00\" sifObcina=\"000\" sifPosta=\"0000\" sifUlica=\"0000\" sifNaselje=\"000\" stHisna=\"000\" sifHsmid=\"00000000\"><Obcina>UNKNOWN</Obcina><Posta>UNKNOWN</Posta><Ulica>UNKNOWN</Ulica><Naselje>UNKNOWN</Naselje></Naslov></Imetnik></Tr>
Maybe this is what you are looking for? Example here: http://ideone.com/N4jIO
import java.io.ByteArrayInputStream;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class Main {
public static void main(String... args) throws IOException, SAXException, ParserConfigurationException {
String xml = "<Tr rn=\"000000000000000\" vr=\"T\" sSpre=\"S\" reg=\"P\" dSpre=\"2000-01-01\" dOdprt=\"2000-01-01\" iban=\"SI00\" eno=\"R\" vir=\"B\" maticnaPps=\"0000000000\"><Imetnik davcna=\"00000000\" matSub=\"0000000000\" drz=\"705\"><PopolnoIme>UNKNOWN</PopolnoIme><KratkoIme>UNKNOWN</KratkoIme><Naslov sifTipNaslova=\"00\" sifObcina=\"000\" sifPosta=\"0000\" sifUlica=\"0000\" sifNaselje=\"000\" stHisna=\"000\" sifHsmid=\"00000000\"><Obcina>UNKNOWN</Obcina><Posta>UNKNOWN</Posta><Ulica>UNKNOWN</Ulica><Naselje>UNKNOWN</Naselje></Naslov></Imetnik></Tr>";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new ByteArrayInputStream(xml.getBytes("UTF-8")));
print(doc.getDocumentElement(), "");
}
private static void print(Node e, String tab) {
if (e.getNodeType() == Node.TEXT_NODE) {
System.out.println(tab + e.getNodeValue());
return;
}
System.out.print(tab + e.getNodeName());
NamedNodeMap as = e.getAttributes();
if (as != null && as.getLength() > 0) {
System.out.print(" attributes=[");
for (int i = 0; i < as.getLength(); i++)
System.out.print((i == 0 ? "" : ", ") + as.item(i));
System.out.print("]");
}
System.out.println();
if (e.getNodeValue() != null)
System.out.println(tab + " " + e.getNodeValue());
NodeList childs = e.getChildNodes();
for (int i = 0; i < childs.getLength(); i++)
print(childs.item(i), tab + " ");
}
}
If your goal is to load/parse an XML Document from a String object, you'll simply need to use the usual XML document loading code, but to use a StringReader to provide your inputstream. (or a ByteArrayInputStream, or anything really as long as you build up a chain of transformations that lets your access your data as an InputStream).
An example follows here (untested and without exception handling. Sorry, I don't have a test environment at the moment):
final DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
final DocumentBuilder db = f.newDocumentBuilder();
final InputSource is = new InputSource();
is.setCharacterStream(new StringReader(YOURSTRING));
final Document doc = db.parse(is);
doc.getDocumentElement().normalize();
/*
* do whatever you want/need here.
*/
If that's not what you wanted, sorry I am not quite sure what you were asking here.
Using xerces could be more understandable:
public static void loadImetniks(String filePath) {
File xmlFile;
SAXBuilder builder;
Element root, child;
Imetnik imet;//another class that you have to create to help you for parsing
Document doc;
try {
xmlFile = new File(filePath);
builder = new SAXBuilder(); // parameters control validation, etc
doc = builder.build(xmlFile);
root = doc.getRootElement(); // Tr could be the root but I am not sure if you will have more Tr nodes in the same file??
tr.setRn(root.getAttributeValue(Constants.RN));//define the constants string in another file
tr.setVr(root.getAttributeValue(Constants.VR));
tr.setSspre(root.getAttributeValue(Constants.SSPRE));
tr.setReg(root.getAttributeValue(Constants.REG));
tr.setIban(root.getAttributeValue(Constants.IBAN));
.... //repeat for every attribute
....
List children = root.getChildren(); // depends of how many Imetnik you will have
for (Iterator iter = children.iterator(); iter.hasNext();) {
child = (Element) iter.next();
imet = new Imetnik();
imet.loadXML(child); // you have to define the loadXML function in your object Imetnik which should extract the attributes and internal nodes
//imets.add(contest); // just use in the case that you will have to extract more than one Imetnik node
}
} catch (Exception e) {
log.error("Error al hacer el parsing del contests.xml!");
log.error(e.getMessage());
}
}
For instance, your Imetnik class should contain:
public void loadXML(Element root) {
Element child;
//Naslov naslov; // for Naslov because it could be an object itself
davcna = root.getAttributeValue(Constants.DAVCNA); //define the string constant
matSub = root.getAttributeValue(Constants.MATSUB); //define the string constant
drz = Integer.parseInt(root.getAttributeValue(Constants.DRZ)); //define the string constant
List children = root.getChildren(); // your root is Imetnik now
for (Iterator iter = children.iterator(); iter.hasNext();) {
.....
.......
}
}
The best solution to parse XML files in Java is to use a dedicated library such as:
Xerces
Sax

Categories