Creating an xml file from java.
I trying to create an xml file using a java program. I just wondering what is the best way to go about it and what should i use jdom ,xerces sax etc.
Use JAXP+SAX.
Here an example:import java.io.*;
// SAX classes.
import org.xml.sax.*;
import org.xml.sax.helpers.*;
//JAXP 1.1
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;
import javax.xml.transform.sax.*;
// PrintWriter from a Servlet
PrintWriter out = response.getWriter();
StreamResult streamResult = new StreamResult(out);
SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
// SAX2.0 ContentHandler.
TransformerHandler hd = tf.newTransformerHandler();
Transformer serializer = hd.getTransformer();
serializer.setOutputProperty(OutputKeys.ENCODING,"ISO-8859-1");
serializer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,"users.dtd");
serializer.setOutputProperty(OutputKeys.INDENT,"yes");
hd.setResult(streamResult);
hd.startDocument();
AttributesImpl atts = new AttributesImpl();
// USERS tag.
hd.startElement("","","USERS",atts);
// USER tags.
String[] id = {"PWD122","MX787","A4Q45"};
String[] type = {"customer","manager","employee"};
String[] desc = {"Tim@Home","Jack&Moud","John D'o�"};
for (int i=0;i<id.length;i++)
atts.clear();
atts.addAttribute("","","ID","CDATA",id);
atts.addAttribute("","","TYPE","CDATA",type[i]);
hd.startElement("","","USER",atts);
hd.characters(desc[i].toCharArray(),0,desc[i].length());
hd.endElement("","","USER");
hd.endElement("","","USERS");
hd.endDocument();
[i]This xml generation program might be the best solution because it uses JAXP 1.1 so it will work under JDK 1.4 or JDK 1.2/1.3 with XALAN2 library (or any XML library JAXP 1.1 compliant). It's also memory-friendly because it doesn't need DOM.
See http://www.javazoom.net/services/newsletter/xmlgeneration.html
Hope That Helps
Similar Messages
-
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 -
I'm a new user of XML. I've a very important question:
Is it possible create an XML file using some java package? If yes what package i must use? JDOM is the right product?
ThanksYes, JDOM is the right choice for 99% of your work.
DOM is too difficult to use.
That is the reason why JDOM has been developped. -
Create dynamically xml file from java.
Hi all,
I got class information in java program. I have to put method name and return type into xml. The xml file is like this and i have created this file.
<method>
<name></name>
<returnType></returnType>
</method>
Now when I get method information I want to put it in xml, not by writing each method name explicitly in file, mean i have to load this xml into memory for that what should i do?
Please help me I am new in XML.
Thanks in advance.
-regards
buntyIf you save your XML file as "methodinfo.xml", you can use the following code:import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder parser = factory.newDocumentBuilder();
Document doc = parser.parse(new File("methodinfo.xml"));
Node nameNode = doc.getElementsByTagName("name").item(0);
Node returnTypeNode = doc.getElementsByTagName("returnType").item(0);
nameNode.setTextContent("the name of the method");
returnTypeNode.setTextContent("the return type of the method");
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(System.out);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
System.out.println("This is the content of the XML document:\n");
transformer.transform(source, result);
catch (Exception e){
...The content of the XML document will be displayed as follows:<?xml version="1.0" encoding="UTF-8" ?>
<method>
<name>the name of the method</name>
<returnType>the return type of the method</returnType>
</method> -
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();
} -
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 -
Creating an xml file from abap code
Hello All,
Please let me know which FM do I need to execute in order to create an XML file from my ABAP code ?
Thanks in advance,
Paul.This has been discussed before
XML files from ABAP programs -
Generation of xml file from java code
hi,
I want to manipulate data in a xml file with java code.I have read data from xml file and also changed it. But i am unable to covert it again in xml file from java code. Can you please tell me how i can do this?Let me know which parser are you using currently for reading xml files so that i assist you. For now, you can refer to STAX Parser API under this link
http://java.sun.com/webservices/docs/1.6/tutorial/doc/SJSXP3.html -
Creating an xml file from recordset
Hi...
XML newbie here - so.
Is it possible to create and xml file from a recordset?
I need to create a datafeed of our e-commerce products.
Also, some of the db data contains HTML Code (product
description field),
how will this effect the xml file?
Another problem is that my xml file needs to contain url's
for the products
and product images. My ASP pages contain these URL in hard
code and then
pull the actual file names from the db
Hope that makes some sense
Thanks for any help
AndyHi David
Thanks for your help.
I think it will have to be option 1 as i am using Access DB.
I don't know how to go about it but will serach good old
Google.
Here is my recordset below, that pulls the required data from
Access.
The product and product image URL's need to be in the xml
file but only the
product image name and product id are in the database, e.g
image name
(imagename.jpg) productid (21)
The actual URL's are hardcoded in my ASP pages, e.g <img
src="products/medium/<%=(RSDetails.Fields.Item("Image").Value)%>"
Not sure if this makes things any clearer :-|
Thanks Again
Andy
<%
Dim RSdatafeed
Dim RSdatafeed_numRows
Set RSdatafeed = Server.CreateObject("ADODB.Recordset")
RSdatafeed.ActiveConnection = MM_shoppingcart_STRING
RSdatafeed.Source = "SELECT Products.Product,
Products.Description,
Products.Image, Products.image2, Products.ListPrice,
Products.Price,
Products.xml_feed, Manufacturers.Manufacturer,
Shipping.ShippingCost FROM
Shipping, Products INNER JOIN Manufacturers ON
Products.ManufacturerID =
Manufacturers.ManufacturerID WHERE
(((Products.xml_feed)=No));"
RSdatafeed.CursorType = 0
RSdatafeed.CursorLocation = 2
RSdatafeed.LockType = 1
RSdatafeed.Open()
RSdatafeed_numRows = 0
%>
"DEPearson" <[email protected]> wrote in
message
news:[email protected]...
> Andy,
>
> There are two ways you can create a xml file from a
recordset
>
> 1. Is to code it using Server.CreateObject(XMLDOM)
> 2. If you are using SQL server 2005, just request the RS
returns as XML
> data. using FOR XML AUTO after the where cause ( the
best way with 2005
> and
> higher sql server)
>
> The db data containing HTML code should not effect your
xml file, unless
> it
> is bad markup. You could wrap the data with
<![CDATA[the data or html
> markup, or javascript]]>
>
> If the url is a recordset field, then it will return
with the xml data.
> If
> not you can create a storage procedure that will build
your URL from the
> data
> in the database.
>
> It is best to use storage procedure (SP )for security
reason when pulling
> data
> from a MS Sql server, make all calls to the database in
a SP. Also be sure
> to
> validate the values in the querystrings before accepting
them, check for
> hack
> code.
>
> David
> -
Create a xml file from an internal table: CALL TRANSFORMATION
Hello gurus,
I want to create a xml file using data from scustom table. I will create an internal table and will select some records to it.
I searched the forum and i discovered the call transformation, but when i execute the example program at the CALL TRANSFORMATION shows a dump screen.
How we create a xml file from internal table??
Please help me. I will mark the useful answers.I'm using if_ixml class to create xml documents
TYPES: BEGIN OF xml_line,
data(256) TYPE x,
END OF xml_line.
DATA: o_ixml TYPE REF TO if_ixml,
o_document TYPE REF TO if_ixml_document,
o_element TYPE REF TO if_ixml_element,
o_streamfactory TYPE REF TO if_ixml_stream_factory,
o_ostream TYPE REF TO if_ixml_ostream,
o_renderer TYPE REF TO if_ixml_renderer.
DATA: t_xml_table TYPE TABLE OF xml_line,
v_xml_size TYPE i.
o_ixml = cl_ixml=>create( ).
o_document = o_ixml->create_document( ).
* The o_document have a set of methods to add elements, attributes, etc.
o_element = o_document->create_simple_element(
name = 'RootNode'
value = 'some text'
parent = o_document ).
o_streamfactory = o_ixml->create_stream_factory( ).
o_ostream = o_streamfactory->create_ostream_itable( table = t_xml_table ).
o_renderer = o_ixml->create_renderer( ostream = o_ostream document = o_document ).
o_renderer->render( ).
v_xml_size = o_ostream->get_num_written_raw( ).
CALL METHOD cl_gui_frontend_services=>gui_download
EXPORTING
bin_filesize = v_xml_size
filename = 'C:a.xml'
filetype = 'BIN'
CHANGING
data_tab = t_xml_table. -
Creating an xml file from a playlist - message for iTunes staff
When I created an xml file from a playlist I noticed that in the xml file the track name was merged with the artist name in this manner "I want you - Bob Dylan".
That was hardly a problem as I could easily correct this in the FileMaker Pro environment.
But subsequently I found out, that within iTunes the track name was similarly changed to the same format. Apparently this happened when iTunes created the xml file and inadvertently also changed the track name within iTunes.
It can easily be corrected by entering File/Info, but I had over 10.000 songs in that list and it will take a lot of time. I have to do this, as I created earlier for each song a file path in FileMaker Pro, which are unrecognizable now.
Could you please correct the xml file creating procedure?I must confess that I can't reproduce this result myself anymore.
I created the xml file in iTunes via File/Library/Export Playlist/xml structure (I translate the Dutch terms loosely) and subsequently I imported the xml file into a Filemaker Pro via File/Import/xml.
The xsl style sheet looks ok.
It looks like a freak of nature.
Still I have the evidence in my iTunes playlist, where I have another 9000 clicks to go to repair the damage.
Let's forget about it, until it happens again.
Thanks for your time. -
Hello
My objective is to have a xml file created from a list for anonymous access. The SharePoint RSS feed is a .aspx file not xml, as shown below:
_layouts/listfeed.aspx?List=21c2cdaa%2D52f3%2D4057%2Db674%2D45e63ba77e31&View=535eb328%2Db5fb%2D45c5%2D8fe8%2Da130e92afc41
Also, is there a way to do this so that the xml content has current data like the list.
Thank you for any insight and direction.Hi,
According to your post, my understanding is that you wanted to create a xml file from a SharePoint list.
To generate a XML file, we can use the SharePoint Object Model or PowerShell to achieve it.
Generate a hierarchical XML file from SharePoint list using Client Object Model.
http://maxderungs.wordpress.com/2012/05/12/generate-a-hierarchical-xml-file-from-sharepoint-list/
Get SharePoint list items and export them to XML using PowerShell
http://www.robertkuzma.com/2012/09/get-sharepoint-list-items-and-export-them-to-xml-using-powershell/
More reference:
http://www.robertkuzma.com/2010/08/how-to-create-a-custom-xml-output-using-sharepoint-services-3-0/
http://traceynolte.com/blog/convert-sharepoint-list-to-xml/
Thanks & Regards,
Jason
Jason Guo
TechNet Community Support -
Creating an xml file from the Basic java Object
how to create an XML file using the values available in the object with reference to an xsd or dtd file..
(OR )
is it possible to write the contents of an object to an xml file without knowing the dtd or xsd file .......how to create an XML file using the values available in the object with reference to an xsd or dtd file..
(OR )
is it possible to write the contents of an object to an xml file without knowing the dtd or xsd file .......
Maybe you are looking for
-
Home Screen Icons & Their Meaning???
Hi, I have an arrow pointing to approx. 1 O'clock at the top right of my home screen, just left of the bluetooth icon. I assume it is something to do with the email but really have no idea - Anybody know? Anybody know how to get rid of it? Many Tha
-
Guys, My DTP failed 4 days back, but the full load from Source system to PSA is executing successfully. To correct the DTP load, I have deleted the last DTP request and also all the PSA requests except the last one and when I re-executed the DTP I am
-
Quicker way to collect checkbox inputs?
I will have a number of checkbox inputs on my JSP page. The idea is an admin clicks on multiple checkboxes and then clicks a Delete button. Is there a slicker way of displaying each checkbox and then collecting the ones whose values marked as true th
-
Desk top folder won't open when I double-click on them
It just started happening, but now when I double-click on my desktop folders, they will not open. I end up having to right-click on them which can be very time consuming and frustrating, to say the least! I'm not sure if it is something I need to fix
-
When I do a search the results are displayed by name or date order (that seems to be the only available options), but the date used is the modification date - at least, that's what shows in the window I have. How do I get it to show and sort by the c