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/]).
Similar Messages
-
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 -
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 -
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.
-
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 -
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 search and replace in an xml file using java
Hi all,
I am new to java and Xml Programming.
I have to search and replace a value Suresh with some other name in the below xml file.
Any help of code in java it is of great help,and its very urgent.
I am using java swings for generating two text boxes and a button but i am not able to search in the xml file thru the values that are entered into these text boxes.
Thanks in advance.
**XML File*
<?xml version="1.0" encoding="ISO-8859-1"?>
<student>
<stud_name>Suresh</stud_name>
<stud_age>40</stud_age>
</student>Also i am using SAX Parser in the java program
any help of code or any tutorials for sax parisng is very urgent please help me to resolve this problem
Edited by: Karthik84 on Aug 19, 2008 1:45 AM
Edited by: Karthik84 on Aug 19, 2008 3:15 AMUsing XPath to locate the elements you are after is very easy.
Try something like this:
import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
public class BasicXMLReplaceWithDOM4J {
static String inputFile = "C:/student.xml";
static String outputFile = "C:/studentRenamed.xml";
public static void main(String[] args) throws Exception {
// Read xml and build a DOM document
Document doc = DocumentBuilderFactory.newInstance()
.newDocumentBuilder().parse(new InputSource(inputFile));
// Use XPath to find all nodes where student is named 'Suresh'
XPath xpath = XPathFactory.newInstance().newXPath();
NodeList nodes = (NodeList)xpath
.evaluate("//stud_name[text()='Suresh']", doc, XPathConstants.NODESET);
// Rename these nodes
for (int idx = 0; idx < nodes.getLength(); idx++) {
nodes.item(idx).setTextContent("Suresh-Renamed");
// Write the DOM document to the file
Transformer xformer = TransformerFactory.newInstance().newTransformer();
xformer.transform(new DOMSource(doc), new StreamResult(new File(outputFile)));
}- Roy
Maybe you are looking for
-
i bought an eBook from iTunes. I can view/read it perfectly on my iPhone but when I try to open the eBook file on my iPad, I get the error message, "Cannot open book. This book is protected by an incompatible technology." Any ideas for me? thx
-
Why does not my Pages app work?
I have got a problem with Pages. Since I have been using the IWork for many years, I am aware how to do it. Now I updated the apps and I can not open it when I turn on the ICloud. There is no problem with Keynote and numbers. Only the Pages. When I
-
Manually sort files in a folder
Is there anyway to sort files in a folder manually? Say I have 4 files. The would be arranged.. File A File B File C File D I want them to be File B File D File A File C Is there ANYWAY to do this? I can't sort them by size or anything like that caus
-
Hi During message mapping normally we do element to element mapping. But could you please tell me when we will go for root node to root node mapping ?? Is it like that when the target root node's cardinality is greater than 1 we will go for root node
-
Editing multiple photos?
Hi there is it possible to apply an edit setting to multiple photos? I probably want to just apply an "enhance" to about 500. Or do I need to do all this individually? Thanks Pete