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("----------------------------");
}
}
Related
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.
Can we search a element by id in xml file using dom parser, for example :
<root>
<context id="one">
<entity>
<identifier>new one</identifier>
</entity>
</context>
<context id="two">
<entity>
<identifier>second one</identifier>
</entity>
</context>
</root>
I want a node with id = "one", my code
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document document = docBuilder.parse(new File("filename.xml"));
Element ele = document.getElementById("one");
return null,
is there any other way?
From the documentation for Document.getElementById
Note: Attributes with the name "ID" or "id" are not of type ID unless so defined.
The problem is the Document doesn't know that an attribute called id is an identifier unless you tell it. You need to set a schema on the DocumentBuilderFactory before you call newDocumentBuilder. That way the DocumentBuilder will be aware of the element types.
In the schema you will need something like this in the appropriate place:
<xs:attribute name="id" type="xs:ID"/>
You could use the javax.xml.xpath APIs in the JDK/JRE to find the element by XPath.
Example
import java.io.File;
import javax.xml.parsers.*;
import javax.xml.xpath.*;
import org.w3c.dom.*;
public class Demo {
public static void main(String[] args) throws Exception {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document document = docBuilder.parse(new File("filename.xml"));
XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath();
Element element = (Element) xpath.evaluate("//*[#id='one']", document, XPathConstants.NODE);
}
}
You could instead use a third party library like Jsoup that does the job rather quite well.
File input = new File("/tmp/input.xml");
Document doc = Jsoup.parse(input, "UTF-8", "test");
And then you could use something like this:
doc.select("context#id=one")
Does that answer your question?
try and use XML - Xpath expression it is very easy
File fXmlFile = new File("filePath");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
String expression;
Node node;
// 1. elements with id '1'
expression = "//context[#id='one']";
node = (Node ) xpath.evaluate(expression, doc, XPathConstants.NODE);
I have the following xml file from vimeo: http://vimeo.com/api/v2/video/21331554.xml
I'm trying to extract the thumbnail-medium with the following code:
File fXmlFile = new File("http://vimeo.com/api/v2/video/" + linkId + ".xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
return ((Node) doc.getElementsByTagName("thumbnail_medium")).getNodeValue();
But i get "undefined" as a return
You cannot cast a NodeList to Node so this line:
return ((Node) doc.getElementsByTagName("thumbnail_medium")).getNodeValue();
throws a ClassCastException. So you need to get the only item in the NodeList and get its text value with this line:
return doc.getElementsByTagName("thumbnail_medium").item(0).getTextContent();
I tested this with this two methods:
#Test
public void domTestVimeo() throws ParserConfigurationException,
SAXException, IOException {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new ClassPathResource("vimeo.xml")
.getInputStream());
doc.getDocumentElement().normalize();
String val = ((Node) doc.getElementsByTagName("thumbnail_medium"))
.getNodeValue();
System.out.println(val);
}
And
#Test
public void yourTest() throws ParserConfigurationException, SAXException,
IOException {
// File fXmlFile = new File("http://vimeo.com/api/v2/video/" + 21331554
// + ".xml");
InputStream is = new ClassPathResource("vimeo.xml").getInputStream();
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(is);
doc.getDocumentElement().normalize();
String val = doc.getElementsByTagName("thumbnail_medium").item(0)
.getTextContent();
System.out.println(val);
}
The first throws a ClassCastException and the second prints http://b.vimeocdn.com/ts/137/151/137151977_200.jpg I think that is the value you are looking for.
Also, how did you read from a File object passing a a URL?
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.
I'm following this turorial on parsing XML with XPath, and it gives the following example to open a document:
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true); // never forget this!
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse("books.xml");
What I would like to do, is change that so that the Document is reading a String variable that I already have made, instead of reading from a file. How can I do that?
builder.parse(new InputSource(new StringReader("<some><xml></xml></some>")));
Look here
DocumentBuilderFactory dbf =
DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xmlRecords));
Document doc = db.parse(is);
You may try this one:
public static Document stringToDom(String xmlSource)
throws SAXException, ParserConfigurationException, IOException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
return builder.parse(new InputSource(new StringReader(xmlSource)));
}