Creating XML files in Java
i am new to java progamming. I have created project using swing and JDBC. Now I want to do some modifications in that project and want create an XML file for the same. I don't know which API to use. Through googling i have only found information on Jave EE and web services. I am using jdk 1.5. Please help.
Ashish
Novice_Ashish wrote:
want create an XML file for the same
Ashishplease elaborate your needs,
if you need to deal with xml
then xerces
Similar Messages
-
Creating XML file from Java Bean
Hi
Are there any standard methods in Java 1.5 to create XML file from java bean,
i can use JAXB or castor to do so,
But i would like to know if there is any thing in java core classes,
I have seen XMLEncoder, but this is not what i want.
Any ideas
AshishMarshall JavaBean to an XML document with JAXB or XMLBeans.
-
Hi all i am working to create a XML file using java can any one show me some sample code how to do so
All I suggested was to insert a single line ("X.serialize(root);") into your code. Anyway, here's a ready-to-compile source code based on yours. This code utilizes the Xerces-J class library.import java.io.File;
import java.io.FileWriter;
import org.apache.xerces.dom.DocumentImpl;
import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
import org.w3c.dom.Element;
public class Test {
public static void main(String[] arguments) {
FileWriter out;
DocumentImpl d;
Element root;
XMLSerializer X;
try {
System.out.println(" creatin ");
File fos = new File("xsr.xml");
out = new FileWriter("xsr.xml");
System.out.println("created File .." + fos.getName());
out.flush();
d = new DocumentImpl();
System.out.println("create root");
root = d.createElement("abc");
System.out.println("creating element");
d.insertBefore(root, null);
//out.write(d.createAttribute(""));
OutputFormat o = new OutputFormat(d);
System.out.println("Output format...");
o.setIndent(5);
o.setIndenting(true);
o.setDoctype("lab1.dtd", "lab1.dtd");
o.setDoctype("name of dtd file", "name of dtd file");
X = new XMLSerializer(o);
X.setOutputCharStream(out);
X.serialize(root);
out.flush();
out.close();
catch (Exception e1){
e1.printStackTrace();
} -
I m not able to create xml file in Java Project
hi all,
I have created one java project just to try with Ant Builder. I have created one class inside it. and now i m creating an XML file inside that project.
But as soon as i try to create the File -> New -> File and give the .xml extention of the file this gives error into the project.
Will you suggest me the solution for that?
Thanks in advance.Assuming that you are facing this problem in NDS, here is the solution.
Go to Windows--> Preferences --> WorkBench -->File Associations
In the File Types list select *.xml
This will display the default associated XML editor as
XML Editor(default) in the bottom list box.
Click on add button near the bottom list box and select Text Editor, click Ok.You will see one more entry in the list box as "Text Editor".
Select this entry and click on the default button.
Click Ok and close the preferences dialogue.
Now create a new xml file.You wont see the error this time.
Please note that this will treat all simple xml files you will create as TEXT Files and always open with Text Editor.You can override this behaviour with right click on the file and select appropriate editor from the "Open With" context menu.
The error you are talking about is because the XML editor tries to check well-formedness and basic syntax rules for the file that you newly created, actually is a noce feature of the IDE.
Rgds,
Amol -
What the best way to create XML files from JAVA application?
Hi to all,
I need to edit and to create new filex in format of xml. I know to parse, but what would be the best way to do:
1. - Create new file, create like simle text file, or there is some clases that know to do it in more simple way
2.a - Edit XML file, to take some data and add it to the XML in the place I want to.
2.b - Also Edit, but not to add fields, just update some of them.
Code examples or links to samples woul be welcomed.
Best regards, Nick.I have tried working with XML directly using the Java classes but this was a pain. I then looked at DOM4J and JDOM and found JDOM easier to use.
-
how can i create an xml file with some data in java ?
You can use the JAXB API to create a java objects that represent a certain DTD. You can then create the xml file by using these objects to conform to a DTD. Each of the objects effectively represent one element or set of elements in an xml file. See www.java.sun.com/xml and JAXB for more details.
-
How I can create a XML file from java Aplication
How I can create a XML file from java Aplication
whith have a the following structure
<users>
<user>
<login>anyName</login>
<password>xxxx</password>
</user>
</users>
the password label must be encripted
accept any suggestionLet us assume you have all the data from the jsp form in an java bean object..
Now you want a xml file. This can be acheived in 2 ways
1. Write it into a file using java.io classes. Say you have a class with name
write("<name>"+obj.getName+</name>);
bingo you have a flat file with the xml
2. Use data binding to do the trick
will recommend JiBx and Castor for the 2nd option
Regards,
Rajagopal -
Create .xml file from a java file
I wanted to know how can we create a .xml file through java with the given data.
For example: book saler.
data given through java are
1)Sl no
2)Book name
3Book type
4)Book price
i want a xml file generated through the java code
can anyone help me out?i have done like this..
but the problem with this is i want to add more than one book details. i am able to add only one book detais..
package name:createxml
main class:GenerateOrderXml.java
CreateXml.java and order.java
package createxml;
import java.util.Vector;
public class GenerateOrderXml {
public static void main(String[] args) {
try{
Order order= new Order();
CreateXml xml=new CreateXml();
Vector orders=new Vector();
order.setBookName("Java_for_beginers");
order.setAuthorName("Balaguruswamy");
order.setISBN("a123");
order.setNo_of_copies("3");
order.setprice("350");
order.setPublisher("Deepak publishers");
orders.add(0,order);
order.setBookName("Java");
order.setAuthorName("Bala");
order.setISBN("a123");
order.setNo_of_copies("3");
order.setprice("350");
order.setPublisher("Deepak ");
orders.add(1,order);
xml.creatxml(orders);
catch(ArrayIndexOutOfBoundsException e)
e.printStackTrace();
package createxml;
import org.jdom.*;
import org.jdom.output.XMLOutputter;
import java.io.IOException;
import java.util.Vector;
* @author divyashree
* To change the template for this generated type comment go to
* Window - Preferences - Java - Code Generation - Code and Comments
public class CreateXml {
public void creatxml(Vector orders)
try
Element root = new Element("BookSaler");
Order order= new Order();
order=(Order)orders.elementAt(0);
Element BName = new Element("Bookname1");
BName.setText(order.getBookName());
root.addContent(BName);
Element AName = new Element("Authorname");
AName.setText(order.getAuthorName());
BName.addContent(AName);
Element isbn = new Element("ISBN");
isbn.setText(order.getISBN());
BName.addContent(isbn);
Element price = new Element("Price");
price.setText(order.getprice());
BName.addContent(price);
Element publisher= new Element("Publisher");
publisher.setText(order.getPublisher());
BName.addContent(publisher);
order=(Order)orders.elementAt(1);
Element BName1 = new Element("Bookname2");
BName1.setText(order.getBookName());
root.addContent(BName1);
Element AName1 = new Element("Authorname");
BName1.addContent(AName);
Element isbn1 = new Element("ISBN");
isbn.setText(order.getISBN());
Element price1 = new Element("Price");
BName1.addContent(price);
Element publisher1= new Element("Publisher");
BName1.addContent(publisher);
Document doc = new Document(root);
try {
XMLOutputter serializer = new XMLOutputter();
serializer.setIndent(" ");
serializer.setNewlines(true);
serializer.output(doc, System.out);
catch (IOException e)
System.err.println(e);
}catch(ClassCastException e)
e.printStackTrace();
package createxml;
import java.util.Vector;
public class Order {
protected String ISBN="";
protected String BookName="";
protected String AuthorName="";
protected String No_of_copies;
protected String price;
protected String Publisher="";
public String getISBN()
return this.ISBN;
public String getBookName()
return BookName;
public String getAuthorName()
return AuthorName;
public String getNo_of_copies()
return No_of_copies;
public String getprice()
return price;
public String getPublisher()
return Publisher;
public void setISBN(String isbn)
Vector vec_isbn= new Vector();
ISBN=isbn;
public void setBookName(String bookname)
BookName=bookname;
public void setAuthorName(String authorname)
AuthorName=authorname;
public void setNo_of_copies(String no_of_copies)
No_of_copies=no_of_copies;
public void setprice(String Price)
price=Price;
public void setPublisher(String publisher)
Publisher=publisher;
/***************************************************************************/ -
Creating XML file in Project folder thru Java Program
hi,
i need one help. i need to create XML file in web://<Project Folder> in xmII thru Java Program. i created one java code and i am able to access XML file that is in c drive. i created jar file for this and placed as action block in Transaction and this working fine. but problem arises when i give file path in java code as web://<folder name>/file.xml which is in Web folder of project in xMII.
How to access the file that is inside web folder from java code.
regards
senthilHi Senthil,
you can address the files that inside the MII workbench are viewed as "web://..." like this:
http://<server>:<port>/XMII/CM/<Project>/<Folder>/<Filename>
The workbench helps you find the correct filename:
- open the WEB tab in the workbench
- right-click on the filename
- select "Copy Link" from the pop up
Now you have the correct link in your clipboard.You can use the "web://" only inside MII.
Michael -
How to edit the existing data in the XML file from java programming.
Hi all
i am able to create XML file with the sample data as below from java programming.
i need sample code on how to edit the existing data in the XML file?
for example
<?xml version="1.0"?>
<mydata>
<data1>
<key1>467</key1>
<name1>Paul</name1>
<id1>123</id1>
</data1>
<data2>
<key2>467</key2>
<name2>Paul</name2>
<id2>123</id2>
</data2>
</mydata>
i am able to insert the data in the XML.
now i need sample code on how to modify the data in the above XML file from the java programming for only key2,name2,id2 tags only. the remaining tags data in the XML file i want to keep same data except for key2,name2,id2 which are i want to modify from java code
Regards
Sunil
[points will be always rewardable]hi
u need a parser or validate the xml file for to read the xml file from java coding u need for this
xml4j.jar u can download this file from here
http://www.alphaworks.ibm.com/tech/xml4j
or we can use the SAX(simple API for XML)
some sample applications for this
http://www.java-tips.org/java-se-tips/javax.xml.parsers/how-to-read-xml-file-in-java.html
http://www.developertutorials.com/tutorials/java/read-xml-file-in-java-050611/page1.html
http://www.xml-training-guide.com/e-xml44.html
let me know u need any other info
bvr -
How to modify an existing xml file from java code.
Hi
I have worked on creating a new xml file from java code using xmlbeans.But if i try to modify an already existing file using java code I am unable to get errorfree xmlfile.
For example if xml file(studlist.xml) is as below:
<?xml version="1.0" encoding="UTF-8"?>
<StudentList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="D:\kchaitanya\xmlprac1\abc\Studlist.xsd">
<Student>
<Name>ram</Name>
<Age>27</Age>
</Student>
<Student>
<Name>sham</Name>
<Age>26</Age>
</Student>
</StudentList>
Now suppose i have set name to victor using student.setName,
and set age to 20 using setAge from javacode,
the new xml file is as follows:
<?xml version="1.0" encoding="UTF-8"?>
<StudentList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="D:\kchaitanya\xmlprac1\abc\Studlist.xsd">
<Student>
<Name>ram</Name>
<Age>27</Age>
</Student>
<Student>
<Name>sham</Name>
<Age>26</Age>
</Student>
</StudentList>
<Student>
<Name>victor</Name>
<Age>20</Age>
</Student>
As observed this is not a valid xml file.But how can i modify without any errors?I know it's an old post, but I found this while doing a google search for something else, and don't like to leave it un-aswered
Just in case anyone has a similar problem... In this case the new elements have been appended outside of the root element
What you need to do is first get the root element and then append the new children to that, there are several ways of getting the root element, which depend on what you want to do with the elements you get back here's a simple (incomplete) way.
// gets the root element of the specified file (code not shown)
Element rootElement= new SAXReader().read(file).getRootElement();Then just append the new elements as below (this is non-generic code and would need to be modified for your situation)
// write a new student element
Element student = document.createElement("Student"); // creates the new student
rootElement.appendChild(student); // ***appends it to the root element***
Element name = document.createElement("Name"); // creates the name element
name.appendChild(document.createTextNode("Fred")); // adds the name text to the name element
student.appendChild(name); // appends the name to the student
Element age= document.createElement("Age"); // creates the age element
age.appendChild(document.createTextNode("26")); // adds the age text to the age element
student.appendChild(age); // appends the name to the studentThen flush ya buffers or whatever and write the file
Edited by: Dream-Scourge on Apr 23, 2008 11:10 AM -
Create XML file by using servlet
Hi, Is there anyone who sucessfully create XML file by taking parameters from a web form? If so, hope you could share the code with me. I moved the code from the example to servlet. it keeps returning null pointer exception on the root node.
java.lang.NullPointerException: at oracle.xml.classgen.CGDocument.(CGDocument.java:62)
nullHi everybody,<br /><br />the code works good now. so it should be available for everybody who needs it:<br /><br />---------------- my code --------------------------------------<br /><br />var container = "";<br /><br />container = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n";<br />container = container + "<all>\n";<br />container = container + "<header>\n";<br />container = container + "<author>author name</author>\n";<br />container = container + "<authorMail>[email protected]</authorMail>\n";<br />container = container + "</header>\n";<br />container = container + "<body>\n";<br />container = container + "<name>" + value + "</name>\n";<br />container = container + "<adresse>" + value + "</adresse>\n";<br />container = container + "<ort>" + value + "</ort>\n";<br />container = container + "<staat>" + value + "</staat>\n";<br />container = container + "<plz>" + value + "</plz>\n";<br />container = container + "<land>" + value + "</land>\n";<br />container = container + "</body>\n";<br />container = container + "</all>\n";<br /><br />var myDoc = event.target;<br />myDoc.createDataObject("export.xml", container);<br />myDoc.exportDataObject("export.xml");<br /><br />app.mailMsg(false, "mail-address1; mail-address2", "", "",<br />"mail subject", "mail body");<br /><br />---------------- end of my code ------------------------------- <br /><br />now i'm looking for a solution to automatically attach the file to this mail and directls sent it without to call up the mail client.<br />if anybody has got an hint, you're welcome ;-)
-
Create XML File from a specified XSD file
Hi,
I'd like to create an XML document with java. BUT How can we "bind" this creation with a XSD file. Hence, the creation may fail if the XSD binded file is not respected.
So I know how to create XML file but not bind to this creation my proper XSD file (XML schema). With which tool can I do this ?
Thanks.Hi,
I'd like to create an XML document with java. BUT How can we "bind" this creation with a XSD file. Hence, the creation may fail if the XSD binded file is not respected.
So I know how to create XML file but not bind to this creation my proper XSD file (XML schema). With which tool can I do this ?
Thanks. -
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. -
Hi,
Can you any give me some third party libraries widely used to create XML file out of trading information ?
ThanksXML handling has been available in core Java since v1.4.
But if you stick to a third party library, JDOM is fine.
private static String transform( org.w3c.dom.Document doc ) throws Exception
javax.xml.transform.TransformerFactory tf = javax.xml.transform.TransformerFactory.newInstance();
javax.xml.transform.Transformer t = tf.newTransformer();
javax.xml.transform.Source source = new javax.xml.transform.dom.DOMSource( doc );
java.io.StringWriter sw = new java.io.StringWriter();
javax.xml.transform.Result result = new javax.xml.transform.stream.StreamResult( sw );
t.setOutputProperty( javax.xml.transform.OutputKeys.ENCODING, ENCODING );
if ( OMIT_XML_DECLARATION )
t.setOutputProperty( javax.xml.transform.OutputKeys.OMIT_XML_DECLARATION, "yes" );
t.transform( source, result );
String ret = sw.toString();
return ret;
}
Maybe you are looking for
-
Can't open one project in Garageband 2
I can open all my other projects in Garageband except for one (size is 431.2 MB on disk). This just started yesterday. A small Garageband box pops up with the moving diagonal blue & grey stripes, then just sits there until I have to close Garageband
-
There have been 7,039 failed login attempts in the last 30 minutes
Hi, I am trying to find out the cause for an OEM alert we received: There have been 7,039 failed login attempts in the last 30 minutesThe cause is ofcourse known, but I can't find out why the application anyway was able to do 7000+ login attempts wit
-
IMovie 09 Memory-Performance Problems-Desperate for an answer!
I am in the process of using IM09 to create a slideshow using stills combined with music and a couple of movie clips. It is approx. 24 mins in length. I have noticed that performance is getting pretty bad, including lag times in positioning transitio
-
I need to know how to download Adobe Flash Player
Is there anyone that can tell me how to download Adobe Flash Player
-
Old DVD tracker appearing alongside Yosemite upgrade DVD
I upgraded to OS X Yosemite and the old DVD player tracking icon still comes up with the new. It usually goes away if I eject the DVD and reinsert it, but I don't know how to get rid of the old one altogether. Thank you in advance.