Reading an XML file using Java
Dear all,
Currently, I'm planning to write a java program that will read from an xml file. This is my XML file:
<?xml version="1.0"?>
<HUMIDITYMEASURE>
<HUMIDITY>32.0</HUMIDITY>
</HUMIDITYMEASURE>
Now, here is my Java code:
import java.io.*;
class ReadAFile{
public static void main(String[]args){
try{
File myFile=new File("XMLFile.xml");
FileReader fileReader= new FileReader(myFile);
BufferedReader reader = new BufferedReader(fileReader);
String line = "null";
while ((line = reader.readLine()) !=null){
System.out.println(line);
reader.close();
catch(Exception ex){
ex.printStackTrace();
So far the program displays the content of the xml file (with the tags). However, my aim is to make the program display the values, not the tags. For example, in this case, i'd like my program to display the value '32.0' rather than:
<?xml version="1.0"?>
<HUMIDITYMEASURE>
<HUMIDITY>32.0</HUMIDITY>
</HUMIDITYMEASURE>
Can anyone provide me with any advice as to how i can do this please? I tried using the tokenizer and split, but to be honest, they dont really work. If anybody has any suggestions, please reply if possible.
Regards,
I have found the solution to my task.
Many thanks to those who have viewed/replied to my message.
For those of you who may be wondering how the problem was solved, it is useful to refer to some documents relating to Java and XML (as combination).
Imported packages such as:
import java.io.File;
import org.w3c.dom.Document;
import org.w3c.dom.*;
and variations of import javax.xml were used.
The use of Nodes and NodeLists I used to.
Thanks again.
p.s. More details on XML and Java are found on the Sun Website.
Regards,
Raheal
Similar Messages
-
Problem reading an xml file using java
i have a Com File which is called through .Net application and i made another java application that call the same COM file using JNI . but the problem is that the xml format generated from the Com file in case of the .Net application is approx 49.9K and the same Xml file Contents generated through java is half the size of the previous file in .net about 24.9K . I had figured out that the .Net application generates the xml file as unicode format while the java application generates the same xml format as ANSI format which is approx the half of the .Net counterpart .
but the problem now is that i can't deserialize the java generated xml to convert it into its java object using XMLDecoder because it is ill formed xml whereas its tags are well structured .
even when i try to open that .NEt xml file into the IE browser it structures the xml file successfully
while the java xml file version tells me that the file is ill formed knowing that the file is well structured and all the tags are valid.First of, that's not "Unicode" and "ANSI". Those are not really encodings per-se. "Unicode" is sometimes used to refer to UTF-16/UCS-2, and "ANSI" is sometimes used to refer to whatever the current 1-byte encoding of the machine is. But again: Those are not valid encoding names. The encodings used are probably UTF-16 (or UCS-2) and UTF-8, respectively.
Next: unless you tell us some exact error message we can't tell you what went wrong.
And if you want to find out if any given XML file is valid, just run it through some validator (such as [the one from the W3C|http://validator.w3.org/]). -
How to read the data from Excel file and Store in XML file using java
Hi All,
I got a problem with Excel file.
My problem is how to read the data from Excel file and Store in XML file using java excel api.
For getting the data from Excel file what are all the steps i need to follow to get the correct result.
Any body can send me the code (with java code ,Excel sheet) to this mail id : [email protected]
Thanks & Regards,
Sreenu,
[email protected],
india,If you want someone to do your work, please have the courtesy to provide payment.
http://www.rentacoder.com -
How to read a text file using Java
Guys,
Good day!
Please help me how to read a text file using Java and create/convert that text file into XML.
Thanks and God Bless.
Regards,
I-Talkpublic void fileRead(){
File aFile =new File("myFile.txt");
BufferedReader input = null;
try {
input = new BufferedReader( new FileReader(aFile) );
String line = null;
while (( line = input.readLine()) != null){
catch (FileNotFoundException ex) {
ex.printStackTrace();
catch (IOException ex){
ex.printStackTrace();
}This code is to read a text file. But there is no such thing that will convert your text file to xml file. You have to have a defined XML format. Then you can read your data from text files and insert them inside your xml text. Or you may like to read xml tags from text files and insert your own data. The file format of .txt and .xml is far too different.
cheers
Mohammed Jubaer Arif. -
How to write as XML file using java 1.5
hi all,
i am trying to create an XML file using java 1.5. I took a XML creating java file which was working with java 1.4 and ported same file into java 1.5 with changes according to the SAX and DOM implmentation in java 1.5 and tried to compile. But while writing as a file it throws error "cannot find the symbol."
can any body help me out to solve this issue.......
thankx in advance
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.NamedNodeMap;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.DocumentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.helpers.ParserFactory;
import java.io.*;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
Document xmlDoc = db.newDocument();
// this creates the xml document ref
// parent node reference
Element rootnd = (Element) xmlDoc.createElement("ALL_TABLES");
// root node
xmlDoc.appendChild(rootnd);
Element rownd = (Element) xmlDoc.createElement("ROW");
rootnd.appendChild(rownd);
Element statusnd = (Element) xmlDoc.createElement("FILE_STATUS");
rownd.appendChild(statusnd);
statusnd.appendChild(xmlDoc.createTextNode("Y")
FileOutputStream outpt = new FileOutputStream(outdir + "//forbranch.xml");
Writer outf = new OutputStreamWriter(outpt, "UTF-8");
//error is occuring here Since write method is not available in the Document class
xmlDoc.write(outf);
outf.flush();Hi,
when I look in the JDK1.4.2 specification I don't see any write method in the Document interface.
However, your solution is the Transformer class. There you transform your DOM tree into any output you need. Your code sould look something like this: TransformerFactory tf = TransformerFactory.newInstance();
// set all necessary features for your transformer -> see OutputKeys
Transformer t = tf.newTransformer();
t.transform(new DOMSource(xmlDoc), new StreamResult(file));Then you have your XML file stored in the file system.
Hope it helps. -
Exception thrown while reading an XML file using Properties
Exception thrown while reading an XML file using Properties.
Exception in thread "main" java.util.InvalidPropertiesFormatException: org.xml.sax.SAXParseException:
The processing instruction target matching "[xX][mM][lL]" is not allowed.
at java.util.XMLUtils.load(Unknown Source)
<?xml version="1.0"?>
<Config>
<Database>
<Product>FX.O</Product>
<URL>jdbc:oracle:thin:@0.0.0.0:ABC</URL>
</Database>
</Config>Am I missing anything?Thanks a lot for all yr help.I have got the basics of
the DTD
However,when I say thus
<!DOCTYPE Config SYSTEM "c:/PartyConfig">
?xml version="1.0"?>
<Config>
<Database>
<Product>FX</Product>
<URL>jdbc:oracle:thin:@0.0.0.0:ABC</URL>
</Database>
</Config>I get the error
Invalid system identifier: file:///c:/ParyConfig.dtd
Please advise?for goodness sake, how many times do I have to tell you that you can't just expect the Properties class to accept arbitrary XML in any format? it reads XML in the format I linked to, and nothing else. Properties is not a general purpose XML binding. you can't do what you're trying to do with it. read this and in particular pay attention to the following
The XML document must have the following DOCTYPE declaration:
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
Furthermore, the document must satisfy the properties DTD described above.
you are not reading my answers properly, are you? kindly do so -
Merging 2 message history xml files using java
hi., i'm new to xml programming..
well..., i got homework bout it..., and got a lot of problems to write it..
could you help me a favor??
I need to write a homework bout merging 2 MSN mssg history files (xml files) using java.
At least need to maintain their date, time, sender, receiver, and information(sayings)....and are ordered using time..
can u help me??Well, show us what you've got and where you are having difficulty.
-
Where can I find an example of a vi which reads a xml file using the Labview schema (LVXMLSchema.xsd)?
�Unflatten From XML� is of little use in parsing because it requires the data type. So it seems that the user has to parse each data value, and then �Unflatten From XML� can help a little.
I would like to see NI provide a VI for parsing it�s own schema.LabVIEW's XML functions are another way of saving data from controls and indicators that is in a more standardized format. If you look at the Unflatten From XML shipping example, it shows taking the data that you would normally send to a Digital Wveform Graph and converting it to XML instead. This data is then unflattend from XML and wired to the graph. Since you know what you wrote to the file, this is an easy thing to do. If what you are looking for is a way to look at any data in any LabVIEW XML file, then you are right, there is not a VI for that. However, I do not believe that that was the intention of the XML functions in the first place.
By wiriting data in XML, this allows other applications outside of LabVIEW to parse and recognize the dat
a. In LabVIEW, you would already know the types and can place a generic item of that type. The issue of knowing the type is that you need to know the type of the wire that comes out of the Unflatten function so that the VI will compile correctly. You could always choose a variant value to unflatten and then do some parsing to take the variant a part. Maybe this will help you out.
See this example for using the Microsoft parser for XML. (http://venus.ni.com/stage/we/niepd_web_display.DISPLAY_EPD4?p_guid=B123AE0CB9FE111EE034080020E74861&p_node=DZ52050&p_submitted=N&p_rank=&p_answer=)
Randy Hoskin
Applications Engineer
National Instruments
http://www.ni.com/ask -
Reading from XML file using DOM parser.
Hi,
I have written the following java code to read the XML file and print the values. It reads the XML file. It gets the node NAME and prints it. But it returns null when trying to get the node VALUE. I am unable to figure out why.
Can anyone please help me with this.
Thanks and Regards,
Shweta
import java.io.*;
import java.net.*;
import java.util.*;
import oracle.xml.parser.v2.*;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
public class ReadNodes
private static XMLDocument mDoc;
public ReadNodes () {
try {
DOMParser lParser = new DOMParser();
URL lUrl = createURL("mot.xml");
System.out.println("after creating the URL object ");
lParser.setErrorStream(System.out);
lParser.showWarnings(true);
lParser.parse(lUrl);
mDoc = lParser.getDocument();
System.out.println("after creating the URL object "+mDoc);
lParser.reset();
} catch (Exception e) {
e.printStackTrace();
} // end catch block
} // End of constructor
public void read() throws DOMException {
try {
NodeList lTrans = this.mDoc.getElementsByTagName("TRANSLATION");
for(int i=0;i<lTrans.getLength();i++) {
NodeList lTrans1 = lTrans.item(i).getChildNodes();
System.out.println("lTrans1.item(0).getNodeName : " + lTrans1.item(0).getNodeName());
System.out.println("lTrans1.item(0).getNodeValue : " + lTrans1.item(0).getNodeValue());
System.out.println("lTrans1.item(1).getNodeName : " + lTrans1.item(1).getNodeName());
System.out.println("lTrans1.item(1).getNodeValue : " + lTrans1.item(1).getNodeValue());
} catch (Exception e) {
System.out.println("Exception "+e);
e.printStackTrace();
} catch (Throwable t) {
System.out.println("Exception "+t);
public static URL createURL(String pFileName) throws MalformedURLException {
URL url = null;
try {
url = new URL(pFileName);
} catch (MalformedURLException ex) {
File f = new File(pFileName);
String path = f.getAbsolutePath();
String fs = System.getProperty("file.separator");
System.out.println(" path of file : "+path +"separator " +fs);
if (fs.length() == 1) {
char sep = fs.charAt(0);
if (sep != '/')
path = path.replace(sep, '/');
if (path.charAt(0) != '/')
path = '/' + path;
path = "file://" + path;
System.out.println("path is : "+path);
// Try again, if this throws an exception we just raise it up
url = new URL(path);
} // End catch block
return url;
} // end method create URL
public static void main (String args[]) {
ReadNodes mXML = new ReadNodes();
mXML.read();
The XML file that I am using is
<?xml version = "1.0"?>
<DOCUMENT>
<LANGUAGE_TRANS>
<TRANSLATION>
<CODE>3</CODE>
<VALUE>Please select a number</VALUE>
</TRANSLATION>
<TRANSLATION>
<CODE>5</CODE>
<VALUE>Patni</VALUE>
</TRANSLATION>
<TRANSLATION>
<CODE>6</CODE>
<VALUE>Status Messages</VALUE>
</TRANSLATION>
<TRANSLATION>
<CODE>7</CODE>
<VALUE>Progress</VALUE>
</TRANSLATION>
<TRANSLATION>
<CODE>8</CODE>
<VALUE>Create Data Files...</VALUE>
</TRANSLATION>
<TRANSLATION>
<CODE>9</CODE>
<VALUE>OK</VALUE>
</TRANSLATION>
</LANGUAGE_TRANS>
</DOCUMENT>because what you want is not the node value of CODE but the node value of the text nodes into it!
assuming only one text node into it, try this:
System.out.println("lTrans1.item(0).getNodeName : " + lTrans1.item(0).getFirstChild().getNodeValue()); -
How Do I write an XML file using Java?
Hello there!! to everyone reading my post.
I have this project I need to do, and I have no clue where to start, I was wondering if you guys could help me out.
I need to know how to write an XML file using a Java Program, but without using a Third party library.... just using java native APIs.
I will probably take the values to construct the file from a form.
I will certainly appreciate if you could post some sample code for me.
Thank you very much in advance..Hello there!,
I have some doubts about the Tutorial I am currently reading. correct me If I'm wrong, but the section "Write a simple XML file" teaches you how to do so using a text editor. I need to create my XML file from a running Java Program written by myself, that takes the values to build it from some variables.
If I'm totally wrong about what I'm saying, could you please point me to where I can find the information of how to do what I'm asking for, inside the tutorial.
Thank you very much,...
sincerely. -
I need for a simple example of reading a xml file using jdom
Hello
I have been looking for a simple example that uses Jdom to read am xml file and use the information for anything( ), and I just can't find one.since I'm just beggining to understand how things work, I need a good example.thanks
here is just a simple cod for example:
<xmlMy>
<table>
<item name="first" value="123" createdDate="1/1/90"/>
<item name="second" value="456" createdDate="1/4/96"/>
</table>
<server>
<property name="port" value="12345"/>
<property name="maxClients" value="3"/>
</server>
</xmlMy>DaveHi,
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream("my_xml_file.xml");
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally{
if (fileInputStream == null) return;
SAXBuilder saxBuilder = new SAXBuilder();
saxBuilder.setEntityResolver(new EntityResolver() {
public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
return new InputSource(new StringReader(""));
Document document = null;
try {
document = saxBuilder.build(fileInputStream);
} catch (JDOMException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (document == null) return;
Element element = document.getRootElement();
System.out.println(element.getName());
System.out.println(element.getChild("table").getName()); -
Reading/writing PDF files using JAVA
how to read/write a PDF file using java,
while i read a pdf file using BUfferedReader class it gives a list of char. which is not readable.
how to convert those files to readable format.?
is there any special class for doin that.?
plz explain..?is there any special class for doin that.?Yes, I'm sure Google knows a few libraries that ca do that.
-
Read&write Excel file using java
Hi everybody,
I have an assignment about methods that read and write an excel file using java (Eclipse SDK), so if anyone know about that please post the solution as soon as possible.
Thanks
Sendbadhttp://onesearch.sun.com/search/onesearch/index.jsp?qt=read+write+excel&subCat=siteforumid%3Ajava31&site=dev&dftab=siteforumid%3Ajava31&chooseCat=javaall&col=developer-forums
-
Read an XML file with java: Document to Node conversion
Hello,
I want to read an XML file and convert data into a Node instance because I need this for an XForm application.
My code is:
private Node workstationType;
public Node initModel() {
try {
//This one will hold the results
Document document;
//loading from XML File
String fileName="C:\\documents\\iniForm.xml";
FileInputStream inXML = new FileInputStream(fileName);
BufferedReader in = new BufferedReader(new InputStreamReader(inXML));
document = XMLLoader.loadFromStream(in);
} catch (Exception e) {
System.err.println("ERROR:" + e.getMessage());
e.printStackTrace(System.err);
//Create the node for the root, 'typeOfWorkstation'
workstationType = document.getDocumentElement(); //A
//Return the root node
return (workstationType);
The problem: I can convert Node instance to Document instance (line A)
The error message is: "document cannot be resolved".
How can I do that??
Thank you
SylvainHere is my XMLLoader class:
public class XMLLoader {
public static Document loadFromStream(Reader reader) throws Exception {
//Build a DOM document with the reader
//prepare DOM document
DOMImplementation impl;
DocumentBuilder builder;
try {
// Find the implementation
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(false);
factory.setValidating(false);
builder = factory.newDocumentBuilder();
impl = builder.getDOMImplementation();
//Read and parse the XML input stream into a DOM document
Document document = builder.parse(new InputSource(reader));
return document;
} catch (IOException ex) {
throw new RuntimeException(
"[XMLLoader.loadFromFile]: Failed loading the InputStream. Root cause: \n"
+ ex);
} catch (Exception ex) {
throw new RuntimeException(
"[XMLLoader.loadFromFile]: Failed to initialize DOM factory. Root cause: \n"
+ ex); -
How to Update existing XML File Using Java Swing
Hi,
I am reading XML file and getting keywords into JList. When i add some keywords into JList through textfield and remove keywords JList, then after click on save button it should update xml file. How can i do it ?
Please provide me some code tips for updating xml file
This is the code that i am using for reading XML File:
import javax.swing.*;
import java.awt.event.*;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.util.*;
import java.text.Collator;
import java.util.regex.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import com.cloudgarden.layout.AnchorConstraint;
import com.cloudgarden.layout.AnchorLayout;
public class getKeywords extends JFrame implements ActionListener
static JPanel p;
static JLabel lbl;
static JButton btnSave,btnAdd,btnRemove;
static String path;
static Vector v;
static JList lstCur;
static JTextField txtKey;
Document dom;
static image imgval;
NodeList nodelstImage;
static AnchorLayout anchorLay;
private DefaultListModel lstCurModel;
public getKeywords()
super("Current Keywords");
v=new Vector();
p=new JPanel();
txtKey=new JTextField(10);
btnAdd=new JButton("Add");
btnRemove=new JButton("Remove");
btnSave=new JButton("Save");
lbl=new JLabel("Current Keywords");
lstCurModel=new DefaultListModel();
lstCur=new JList();
JScrollPane scr=new JScrollPane(lstCur);
runExample();
lstCur.setModel(lstCurModel);
p.add(lbl);
p.add(scr);
p.add(txtKey);
p.add(btnAdd);
p.add(btnRemove);
p.add(btnSave);
add(p);
btnAdd.addActionListener(this);
btnRemove.addActionListener(this);
btnSave.addActionListener(this);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
public static void main(String arg[])
getKeywords g=new getKeywords();
g.resize(250,400);
g.setVisible(true);
public void actionPerformed(ActionEvent ae)
if(ae.getSource()==btnAdd)
lstCurModel.addElement(txtKey.getText());
if(ae.getSource()==btnRemove)
lstCurModel.remove(lstCur.getSelectedIndex());
if(ae.getSource()==btnSave)
//Code to Write
public void runExample()
//Parse the XML file and get the DOM object
ParseXMLFile();
//Get the Detail of the Image Document
parseImageDocument();
//Get the Detail of the LML Document
//parseLMLDocument();
//System.out.println(lmlval.Title);
public void ParseXMLFile()
//Get the Factory
DocumentBuilderFactory builderFac = DocumentBuilderFactory.newInstance();
try
//Using factory get an instance of the Document Builder
DocumentBuilder builder = builderFac.newDocumentBuilder();
//parse using builder to get DOM representation of the XML file
dom = builder.parse("LML.xml");
catch(ParserConfigurationException pce)
pce.printStackTrace();
catch(SAXException sax)
sax.printStackTrace();
catch(IOException ioex)
ioex.printStackTrace();
public void parseImageDocument()
//Get the root element
Element docImgEle = dom.getDocumentElement();
//Get a nodelist for <Image> Element
nodelstImage = docImgEle.getElementsByTagName("Image");
if(nodelstImage != null && nodelstImage.getLength() > 0)
for(int i = 0; i < nodelstImage.getLength(); i++)
//Get the LML elements
Element el = (Element)nodelstImage.item(i);
//Get the LML object
getImage myImgval = new getImage();
imgval = myImgval.getimage(el);
v.addElement(new String(imgval.Thumb));
String[] x = Pattern.compile(",").split(imgval.Keys);
for (int s=0; s<x.length; s++)
lstCurModel.addElement(x[s].trim());
//System.out.println(x[s].trim());
} Thanks
NitinYou should update your DOM document to represent the changes that you want made.
Then, using the Transformation API you simply transform your document onto a stream representing your file. Something like this:
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
// TODO - set indentation amount!
Source source = new DOMSource(dom);
Result result = new StreamResult(file);
transformer.transform(source, result);Hope this helps.
Maybe you are looking for
-
Do you know why the metadata template in Bridge fails for DNGs?
I am writing in IPTC (IIM, Legacy) and IPTC Core metadata into dng files in Bridge (CS4) using the Metadata Templates, and the template I set up works fine for jpgs but when I try to use it for dngs the captions/keywords get written over using the fi
-
HOW DO I GET RID OF MOBLEME AND START USING MY OUTLOOK WITHOUT A 2 MINUTE DELAY AND MULTIPLE "CLOSE PROGRAM CLICKS"?
-
Problem Opening Site Files in iWeb 3.0.4
Having a problem opening different sites, I use seperate iWeb files for each site in one folder and now only one default site will appear when opening iWeb or trying to open any different site(file). I've done permissions and restarts but still no su
-
LCM: "Download files associated the object" error
All, I am testing on how I can use LCM in my QA process. I was creating a brand new WebI report in development environment and successfully promoted that report to test environment. Then, I modified that WebI report in development. Next, I wanted to
-
Assign new default RSS reader in Mountain Lion
How do I change the default RSS reader under Mountain Lion and Safari 6? Removing the configuration preference from Safari 6 was a BAD IDEA! Anyway, any help will be deeply appreciated. Thanks.