Creating XML in java
hi all,
I am trying to create xml files from java, however I receive the following errors when trying to marshall:
02:23:24.967 [classloader] sharenotes/jaxb.properties -> null
02:23:24.967 [classloader] META-INF/services/javax.xml.bind.JAXBContext -> null
02:23:24.968 [classloader] com.sun.xml.internal.bind.v2.ContextFactory
02:23:24.970 [classloader] sharenotes/jaxb.index -> null
"sharenotes" doesnt contain ObjectFactory.class or jaxb.indexhelloworold
My code looks like this:
public static boolean marshallToFile(String filename, Annotation ann)
try
FileOutputStream stream = new FileOutputStream(filename);
System.out.println(stream);
JAXBContext jc = JAXBContext.newInstance( "sharenotes" );
System.out.println(jc);
Marshaller marshaller = jc.createMarshaller();
//marshaller.marshal(ann, stream);
marshaller.marshal( new JAXBElement(new QName("","Annotation"), Annotation.class, ann ), stream);
stream.close();
catch(Exception ex)
System.out.println(ex.getMessage() + "helloworold");
return false;
return true;
Basically, I am using javascript which calls the methods in java which create the xml files. When I run this as an application in java, everything works fine!
Can someone please help?!?!
Kind regards
Chris
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
-
Hello @ll,
I need a java code to convert XML file ,which has one node to again a XML file with multiple nodes,depends on the content of source XML File....
The source structure is something like this:
<Name>abcd;xyzw;prs</Name>
and the target structure is something like:
<FirstNAme>abcd</FirstNAme>
<MidNAme>xyzw</MidName>
<LastName>prs</LastName>
the length of the data is not fixed. and ";" is used as a seperator.
I have hundred such nodes on the target side.
How do i acheive this
Thanks in Advance.
With Regards,
BVSDEVELOPEMENT-THRILL wrote:
hi ,
what i think he can convert the xml to java object by using xstream then he can do his desired work in java and again he can convert it to xml by using xstream again.
RegardsAn enormous waste of time, though. His "desired" work doesn't need any Java at all, beyond maybe kicking off the transform. Seriously, you've given some poor advice - as we all do from time to time - just accept it rather than try to justify it in retrospect. One of the biggest mistakes you can make as a developer is to use the same tool for everything simply because you already know how to. XSLT and XPath are enormously useful tools to have kicking about, and pretty trivial to learn as well. What could take dozens of lines of Java to achieve could take a single XPath query. Which would you prefer? -
Hi,
I have reached a situation where I have to create small pieces of xml (around 8k characters) within my java app. Right now I am using stringbuffer to create the xml which does not go against a dtd. This is working for now, since I do not have to read in the xml again.
But if I wanted to use some other xml utility like xerces or jdom, is it recommended for my use of xml or would it be an overkill. Please let me know.
Thanks.
tPI am in a similar situation. See my earlier post today . However I am yet to start the design. Can you please pass me your email and we can be in touch? My email is [email protected]
Thanks -
Hi All,
I'm developing a webdynpro component. On click of submit in action I want to create a xml file.
Can anyone tell me how can we achieve this.
Regards,
Nilesh.Hi,
I guess the following links will help you in creating XML.
http://java.sun.com/xml/tutorial_intro.html
http://www.cafeconleche.org/books/xmljava/
http://www.javaworld.com/jw-03-2000/jw-03-xmlsax.html
http://developers.sun.com/sw/building/codesamples/dom/index.html
import org.w3c.dom.Document;
Main class for DOM Sample
public class DOMSample {
File name of Order
static String orderFileName = "Order.xml";
@param args the command line arguments
public static void main(String[] args) {
Document document = null;
Order order = null;
out("\nConstruct document using DOM in memory, save to file, and print it");
// Build new DOM Document
CreateOrderDOM cDOM = new CreateOrderDOM();
document = cDOM.getDocument();
out("New Order created");
// Print XML content
DOMUtil.printDOM(document);
// Write to a file
DOMUtil.writeXmlToFile("newOrder.xml",document);
out("\n\nThe New Order stored to NewOrder.xml");
// Create Order object based on Document
order = new Order(document);
out("\n\nPrint the Order's summary");
order.print();
out("\n\nConstruct document using existing XML Order," +
" apply discount, insert Tax and Total info to the" +
" Order, save to file, and print it");
// Read XML from file to DOM
document = DOMUtil.parse("Order.xml");
if (document != null){
// Print XML content
out("\nPrint XML from file");
DOMUtil.printDOM(document);
// Get Order Price
order = new Order(document);
out("\nPrint the Order's summary");
order.print();
//Calculate total Items in Order
int count = DOMUtil.countByTagName("Item",document);
out("\nNumber Items in Order: " + count);
out("Check for Discount");
// Check for Discount
if (order.isDiscount()){
out("Apply Discount");
order.applyDiscount();
out("\nResult Order");
order.print();
// Add Tax and Total to the Order XML
order.AddTaxAndTotal();
// Print XML content
out("\nPrint XML that include Tax and Total");
DOMUtil.printDOM(document);
// Write to a file
DOMUtil.writeXmlToFile("DiscountOrder.xml",document);
out("\n\nThe Order modified and stored to DiscountOrder.xml");
Prints to the System output a message
@param message String
private static void out(String message) {
System.out.println(message); -
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.
-
Creating a custom java module for excel to xml conversion.
Hi Gurus,
I am creating a custom java module in sap nwds 7.3 for Excel to XML Conversion. But I am getting following error
Classpath dependency validator message.
Classpath entry will not be exported or published. Runtime ClassNotFoundExceptions may result.
I imported the Jars from a different PI system and i am using NWDS in local PC with creating a separate folder with all JARs and also imported them using build path option.
This issue is occuring for all the jars imported.
I am using following code.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;
import com.sap.aii.mapping.api.StreamTransformation;
import com.sap.aii.mapping.api.AbstractTrace;
import java.util.HashMap;
import jxl.Cell;
import jxl.Workbook;
public class JavaMappingExcelToXML implements StreamTransformation{
private Map map = null;
private AbstractTrace trace = null;
public void setParameter(Map arg0) {
map = arg0; // Store reference to the mapping parameters
if (map == null) {
this.map = new HashMap();
public static void main(String args[]) { //FOR EXTERNAL STANDALONE TESTING
try {
FileInputStream fin = new FileInputStream ("c:/ashu.xls"); //INPUT FILE (PAYLOAD)
FileOutputStream fout = new FileOutputStream ("C:/Users/ashutosh.a.upadhyay/My Documents/ashuXML2.xml"); //OUTPUT FILE (PAYLOAD)
JavaMappingXLStoXML mapping = new JavaMappingXLStoXML ();
mapping.execute(fin, fout);
catch (Exception e1) {
e1.printStackTrace();
public void execute(InputStream inputstream, OutputStream outputstream) {
String msgType = "Message Type name will come here";
String nameSpace = "Namespace Name will come here";
String xmldata = "";
try {
Workbook wb = Workbook.getWorkbook(inputstream);
xmldata ="<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+ "<ns0:"+msgType+" "+"xmlns:ns0=\""+nameSpace+"\n">";
Cell[] cells ;
Cell[] cellNames ;
cellNames = wb.getSheet(0).getRow(0);
for(int j=1;j<wb.getSheet(0).getRows();j++){
xmldata = xmldata+"\n<Record>\n";
cells = wb.getSheet(0).getRow(j);
for(int i=0;i<wb.getSheet(0).getColumns();i++){
xmldata = xmldata+"\t<"+cellNames[i].getContents()+">"+cells[i].getContents()+"</"+cellNames[i].getContents()+">\n";
xmldata = xmldata+"</Record>";
xmldata = xmldata+"\n</ns0:"+msgType+">";
System.out.print(xmldata);
xmldata.getBytes();
wb.close();
byte by[] = xmldata.getBytes();
outputstream.write(by);
inputstream.close();
outputstream.close();
System.out.println("\n"+"File processed");
catch (Exception e) {
e.printStackTrace();
Request you to guide how to resolve this issue.
Thanks in advanceHi Gurus,
I am creating a custom java module in sap nwds 7.3 for Excel to XML Conversion. But I am getting following error
Classpath dependency validator message.
Classpath entry will not be exported or published. Runtime ClassNotFoundExceptions may result.
I imported the Jars from a different PI system and i am using NWDS in local PC with creating a separate folder with all JARs and also imported them using build path option.
This issue is occuring for all the jars imported.
I am using following code.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;
import com.sap.aii.mapping.api.StreamTransformation;
import com.sap.aii.mapping.api.AbstractTrace;
import java.util.HashMap;
import jxl.Cell;
import jxl.Workbook;
public class JavaMappingExcelToXML implements StreamTransformation{
private Map map = null;
private AbstractTrace trace = null;
public void setParameter(Map arg0) {
map = arg0; // Store reference to the mapping parameters
if (map == null) {
this.map = new HashMap();
public static void main(String args[]) { //FOR EXTERNAL STANDALONE TESTING
try {
FileInputStream fin = new FileInputStream ("c:/ashu.xls"); //INPUT FILE (PAYLOAD)
FileOutputStream fout = new FileOutputStream ("C:/Users/ashutosh.a.upadhyay/My Documents/ashuXML2.xml"); //OUTPUT FILE (PAYLOAD)
JavaMappingXLStoXML mapping = new JavaMappingXLStoXML ();
mapping.execute(fin, fout);
catch (Exception e1) {
e1.printStackTrace();
public void execute(InputStream inputstream, OutputStream outputstream) {
String msgType = "Message Type name will come here";
String nameSpace = "Namespace Name will come here";
String xmldata = "";
try {
Workbook wb = Workbook.getWorkbook(inputstream);
xmldata ="<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+ "<ns0:"+msgType+" "+"xmlns:ns0=\""+nameSpace+"\n">";
Cell[] cells ;
Cell[] cellNames ;
cellNames = wb.getSheet(0).getRow(0);
for(int j=1;j<wb.getSheet(0).getRows();j++){
xmldata = xmldata+"\n<Record>\n";
cells = wb.getSheet(0).getRow(j);
for(int i=0;i<wb.getSheet(0).getColumns();i++){
xmldata = xmldata+"\t<"+cellNames[i].getContents()+">"+cells[i].getContents()+"</"+cellNames[i].getContents()+">\n";
xmldata = xmldata+"</Record>";
xmldata = xmldata+"\n</ns0:"+msgType+">";
System.out.print(xmldata);
xmldata.getBytes();
wb.close();
byte by[] = xmldata.getBytes();
outputstream.write(by);
inputstream.close();
outputstream.close();
System.out.println("\n"+"File processed");
catch (Exception e) {
e.printStackTrace();
Request you to guide how to resolve this issue.
Thanks in advance -
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 -
Create XML file from ABAP with SOAP Details
Hi,
I am new to XML and I am not familiar with JAVA or Web Service. I have searched in SDN and googled for a sample program for creating XML document from ABAP with SOAP details. Unfortunately I couldn't find anything.
I have a requirement for creating an XML file from ABAP with SOAP details. I have the data in the internal table. There is a Schema which the client provided and the file generated from SAP should be validating against that Schema. Schema contains SOAP details like Envelope, Header & Body.
My question is can I generate the XML file using CALL TRANSFORMATION in SAP with the SOAP details?
I have tried to create Transformation (Transaction XSLT_TOOL) in SAP with below code. Also in CALL transformation I am not able to change the encoding to UTF-8. It's always show UTF-16.
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:sap="http://www.sap.com/sapxsl" version="1.0">
<xsl:template match="/">
<SOAP:Envelope xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP:Header>
<CUNS:HeaderInfo>
<CUNS:InterfaceTypeId>10006</InterfaceTypeId>
<CUNS:BusinessPartnerID>11223344</BusinessPartnerID>
<CUNS:SchemaVersion>1.0</SchemaVersion>
<CUNS:DateTime>sy-datum</DateTime>
</CUNS:HeaderInfo>
</SOAP:Header>
<SOAP:Body>
<xsl:copy-of select="*"/>
</SOAP:Body>
</SOAP:Envelope>
</xsl:template>
</xsl:transform>
In ABAP program, I have written below code for calling above Transformation.
call transformation ('Z_ID')
source tab = im_t_output[]
result xml xml_out.
call function 'SCMS_STRING_TO_FTEXT'
exporting
text = xml_out
tables
ftext_tab = ex_t_xml_data.
Please help me how to generate XML file with SOAP details from ABAP. If anybody have a sample program, please share with me.
Is there any easy way to create the XML file in CALL Transformation. Please help.
ThanksTry ABAP forum, as it seems not to be PI related.
-
How to generate XML usng java without using following.
import org.apache.xerces.dom.DocumentImpl;
import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
XML to be generated is as follows.
<?xml version="1.0" encoding="UTF-8"?>
<Modi xmlns:xsi="Modi/Modi1">
<docConfig>
<className>PO</className>
<classDesc>Purchase</classDesc>
<create>Y</create>
</docConfig>
<indexConfig>
<index sequence="1">
<shortName>PODATE</shortName>
<displayName>PO Date</displayName>
<type>date</type>
<length>10</length>
</index>
</indexConfig>
</upload>Two answers.
If you want to not use any of the XML-oriented classes, you can use a PrintWriter. Just code:
PrintWriter pw = new PrinteWriter(whatever);
pw.println( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" );
etc.If you want to use XML-oriented classes, but just not these 3 (can't imagine why), then use
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
instead of XMLSerializer and OutputFormat, and
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
instead of the DocumentImpl
Dave Patterson -
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. -
/* Style Definitions */
table.MsoNormalTable
{mso-style-name:"Table Normal";
mso-tstyle-rowband-size:0;
mso-tstyle-colband-size:0;
mso-style-noshow:yes;
mso-style-priority:99;
mso-style-qformat:yes;
mso-style-parent:"";
mso-padding-alt:0in 5.4pt 0in 5.4pt;
mso-para-margin:0in;
mso-para-margin-bottom:.0001pt;
mso-pagination:widow-orphan;
font-size:11.0pt;
font-family:"Calibri","sans-serif";
mso-ascii-font-family:Calibri;
mso-ascii-theme-font:minor-latin;
mso-fareast-font-family:"Times New Roman";
mso-fareast-theme-font:minor-fareast;
mso-hansi-font-family:Calibri;
mso-hansi-theme-font:minor-latin;
mso-bidi-font-family:"Times New Roman";
mso-bidi-theme-font:minor-bidi;}
For the last 5 years (and in IPCC3.x/4.x,UCCX/5.x/7.x) I've used the same basic subflow to read a XML document that contains holiday dates where the queue should be closed. I've re-used this script on 20+ client installs and it's always worked. The structure of the script allows you to pass the path and filename of the XML document as parameters to the subflow. (The document is in the repository)
I loaded this script in UCCX 8.0.2 recently and it crashed with a Java.IO error. It looked like it was trying to read the file system directly and not the repository. (In the Linux appliance model this kind of makes sense but why is the step trying to read the file system directly?)
So I open a TAC case (SR# 615243125) and TAC tells me that the method of using the Create File Document step is not supported anymore and that I should specify the filename directly in the Create XML Document step
The problem that I see (aside from having to edit all my scripts that use XML files) is that the Create XML Document step is looking for the input to be a type DOCUMENT and not a type STRING. This seems to imply that I have to hardcode the document in each script that I deploy for a customer. When it was a string it was easy to construct the full file path from parameters and pass to the subflow.
Questions to the group
#1 Am I missing something here?
#2 Do you assume that you'll be able to load a script that worked fine in UCCX 7 into UCCX 8 and that it should completely function when you're doing everything according to the step reference documentation.
#3 Cisco didn’t document this in any way that I can find.
#4 How can you use the Create XML Document step in a fashion that would let you construct the path of the file and the filename previously in the script so you could pass it to a subflow ? It would seem this functionality has been killed in UCCX 8
/* Style Definitions */
table.MsoNormalTable
{mso-style-name:"Table Normal";
mso-tstyle-rowband-size:0;
mso-tstyle-colband-size:0;
mso-style-noshow:yes;
mso-style-priority:99;
mso-style-qformat:yes;
mso-style-parent:"";
mso-padding-alt:0in 5.4pt 0in 5.4pt;
mso-para-margin:0in;
mso-para-margin-bottom:.0001pt;
mso-pagination:widow-orphan;
font-size:11.0pt;
font-family:"Calibri","sans-serif";
mso-ascii-font-family:Calibri;
mso-ascii-theme-font:minor-latin;
mso-fareast-font-family:"Times New Roman";
mso-fareast-theme-font:minor-fareast;
mso-hansi-font-family:Calibri;
mso-hansi-theme-font:minor-latin;
mso-bidi-font-family:"Times New Roman";
mso-bidi-theme-font:minor-bidi;}
(Background)
Create File Document Step
The input filename is a STRING, could be an explicit path and filename in the repository or a variable that represents that path and string
The output of this step is a DOCUMENT to be used in the Create XML Document step
The string FILE_FullPathHolidayFiles references en_us\folderName\documentName.xml
The document was properly uploaded into the repository only, NOT trying to directly read c:\foo\blah…
/* Style Definitions */
table.MsoNormalTable
{mso-style-name:"Table Normal";
mso-tstyle-rowband-size:0;
mso-tstyle-colband-size:0;
mso-style-noshow:yes;
mso-style-priority:99;
mso-style-qformat:yes;
mso-style-parent:"";
mso-padding-alt:0in 5.4pt 0in 5.4pt;
mso-para-margin:0in;
mso-para-margin-bottom:.0001pt;
mso-pagination:widow-orphan;
font-size:11.0pt;
font-family:"Calibri","sans-serif";
mso-ascii-font-family:Calibri;
mso-ascii-theme-font:minor-latin;
mso-fareast-font-family:"Times New Roman";
mso-fareast-theme-font:minor-fareast;
mso-hansi-font-family:Calibri;
mso-hansi-theme-font:minor-latin;
mso-bidi-font-family:"Times New Roman";
mso-bidi-theme-font:minor-bidi;}
The create XML document input can only be a type DOCUMENT#1 Am I missing something here?
You are mixing two different issues together here.
The Create File Document step is indeed not needed or supported for creating an XML document. That is why there is a unique step; to trigger XML parsing within the MIVR subsystem.
Accessing the file system is restricted to a single folder within the VOS model (i.e. 8.0+). This folder is not backed up, replicated, or cleaned up automatically. It was intended to give developers some FS access as a temporary swap location only.
#2 Do you assume that you'll be able to load a script that
worked fine in UCCX 7 into UCCX 8 and that it should completely
function when you're doing everything according to the step reference
documentation.
Assume nothing; read the documentation and attend one of the dozens of partner training sessions that CCBU put on advising of the upcoming changes.
#3 Cisco didn’t document this in any way that I can find.
You're right, I guess, on the Create File vs. XML Document step. AFAIK Cisco never wrote a notice into the Step Reference Guide explicitly stating that you cannot use the Create File Document although the documentation seemed pretty clear to me without it. File system restrictions are documented in the 8.0 release notes.
Scripting and Development Series: Volume 2, Editor Step ReferenceUse the Create XML Document step to create a logical document that maps a document to another document variable (where the document has already been pre-parsed as an XML document and is ready to be accessed by the Get XML Document Data step).Use this step before the Get XML Document Data step to obtain data from a document formatted using the Extensible Markup Language (XML).
#4 How can you use the Create XML Document step in a fashion that would
let you construct the path of the file and the filename previously in
the script so you could pass it to a subflow ? It would seem this functionality has been killed in UCCX 8
No it hasn't; just concatinate a string to build the Source Document parameter the step needs. Example: "DOC[" + myFilePath + "]" -
How to parse XML to Java object... please help really stuck
Thank you for reading this email...
If I have a **DTD** like:
<!ELEMENT person (name, age)>
<!ATTLIST person
id ID #REQUIRED
>
<!ELEMENT name ((family, given) | (given, family))>
<!ELEMENT age (#PCDATA)>
<!ELEMENT family (#PCDATA)>
<!ELEMENT given (#PCDATA)>
the **XML** like:
<person id="a1">
<name>
<family> Yoshi </family>
<given> Samurai </given>
</name>
<age> 21 </age>
</person>
**** Could you help me to write a simple parser to parse my DTD and XML to Java object, and how can I use those objects... sorry if the problem is too basic, I am a beginner and very stuck... I am very confuse with SAXParserFactory, SAXParser, ParserAdapter and DOM has its own Factory and Parser, so confuse...
Thank you for your help, YoHi, Yo,
Thank you very much for your help. And I Wish you are there...I'm. And I plan to stay - It's sunny and warm here in Honolulu and the waves are up :)
A bit more question for dear people:
In the notes, it's mainly focus on JAXB,
1. Is that mean JAXB is most popular parser for
parsing XML into Java object? With me, definitely. There are essentially 3 technologies that allow you to parse XML documents:
1) "Callbacks" (e.g. SAX in JAXP): You write a class that overrides 3 methods that will be called i) whenever the parser encounters a start tag, ii) an end tag, or iii) PCDATA. Drawback: You have to figure out where the heck in the document hierarchy you are when such a callback happens, because the same method is called on EACH start tag and similarly for the end tag and the PCDATA. You have to create the objects and put them into your own data structure - it's very tedious, but you have complete control. (Well, more or less.)
2) "Tree" (e.g. DOM in JAXP, or it's better cousin JDOM): You call a parser that in one swoop creates an entire hierarchy that corresponds to the XML document. You don't get called on each tag as with SAX, you just get the root of the resulting tree. Drawback: All the nodes in the tree have the same type! You probably want to know which tags are in the document, don't you? Well, you'll have to traverse the tree and ask each node: What tag do you represent? And what are your attributes? (You get only strings in response even though your attributes often represent numbers.) Unless you want to display the tree - that's a nice application, you can do it as a tree model for JTree -, or otherwise don't care about the individual tags, DOM is not of much help, because you have to keep track where in the tree you are while you traverse it.
3) Enter JAXB (or Castor, or ...): You give it a grammar of the XML documents you want to parse, or "unmarshall" as the fashion dictates to call it. (Actually the name isn't that bad, because "parsing" focuses on the input text while "unmarshalling" focuses on the objects you get, even though I'd reason that it should be marshalling that converts into objects and unmarshalling that converts objects to something else, and not vice versa but that's just my opinion.) The JAXB compiler creates a bunch of source files each with one (or now more) class(es) (and now interfaces) that correspond to the elements/tags of your grammar. (Now "compiler" is a true jevel of a misnomer, try to explain to students that after they run the "compiler", they still need to compile the sources the "compiler" generated with the real Java compiler!). Ok, you've got these sources compiled. Now you call one single method, unmarshall() and as a result you get the root node of the hierarchy that corresponds to the XML document. Sounds like DOM, but it's much better - the objects in the resulting tree don't have all the same type, but their type depends on the tag they represent. E.g if there is the tag <ball-game> then there will be an object of type myPackage.BallGame in your data structure. It gets better, if there is <score> inside <ball-game> and you have an object ballGame (of type BallGame) that you can simply call ballGame.getScore() and you get an object of type myPackage.Score. In other words, the child tags become properties of the parent object. Even better, the attributes become properties, too, so as far as your program is concerned there is no difference whether the property value was originally a tag or an attribute. On top of that, you can tell in your schema that the property has an int value - or another primitive type (that's like that in 1.0, in the early release you'll have to do it in the additional xjs file). So this is a very natural way to explore the data structure of the XML document. Of course there are drawbacks, but they are minor: daunting complexity and, as a consequence, very steep learning curve, documentation that leaves much to reader's phantasy - read trial and error - (the user's guide is too simplicistic and the examples too primitive, e.g. they don't even tell you how to make a schema where a tag has only attributes) and reference manual that has ~200 pages full of technicalities and you have to look with magnifying glas for the really usefull stuff, huge number of generated classes, some of which you may not need at all (and in 1.0 the number has doubled because each class has an accompanying interface), etc., etc. But overall, all that pales compared to the drastically improved efficiency of the programmer's efforts, i.e. your time. The time you'll spend learning the intricacies is well spent, you'll learn it once and then it will shorten your programming time all the time you use it. It's like C and Java, Java is order of magnitude more complex, but you'd probably never be sorry you gave up C.
Of course the above essay leaves out lots and lots of detail, but I think that it touches the most important points.
A word about JAXB 1.0 vs. Early Release (EA) version. If you have time, definitively learn 1.0, they are quite different and the main advantage is that the schema combines all the info that you had to formulate in the DTD and in the xjs file when using the EA version. I suggested EA was because you had a DTD already, but in retrospect, you better start from scratch with 1.0. The concepts in 1.0 are here to stay and once your surmounted the learning curve, you'll be glad that you don't have to switch concepts.
When parser job is done,
what kind of Java Object we will get? (String,
InputStream or ...)See above, typically it's an object whose type is defined as a class (and interface in 1.0) within the sources that JABX generates. Or it can be a String or one of the primitive types - you tell the "compiler" in the schema (xjs file in EA) what you want!
2. If we want to use JAXB, we have to contain a
XJS-file? Something like:In EA, yes. In 1.0 no - it's all in the schema.
I am very new to XML, is there any simpler way to get
around them? It has already take me 4 days to find a
simple parser which give it XML and DTD, then return
to me Java objects ... I mean if that kind of parser
exists....It'll take you probably magnitude longer that that to get really familiar with JAXB, but believe me it's worth it. You'll save countless days if not weeks once you'll start developing serious software with it. How long did it take you to learn Java and it's main APIs? You'll either invest the time learning how to use the software others have written, or you invest it writing it yourself. I'll take the former any time. But it's only my opinion...
Jan -
How do I create XML output as string without the ?xml ? tag
I need to create xml from a database query result. I am able to do this but it includes the <?xml ?> header tag. I need to create the xml without the header tag <?xml ?>. Please advise.
Here is my source:
package sql_test;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;
import javax.xml.transform.dom.*;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import java.sql.*;
public class SQLConnector {
java.sql.Connection conn;
public SQLConnector()
conn = null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:mysql://localhost/test", "admin", "admin");
} catch(Exception e) {
System.err.println("Exception: " + e.getMessage());
public String getTestData()
Document doc = null;
Statement s = null;
ResultSet rs = null;
String str = null;
try {
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
doc = builder.newDocument();
Element results = doc.createElement("Results");
doc.appendChild(results);
s = conn.createStatement();
s.executeQuery("select * from test_table");
rs = s.getResultSet ();
ResultSetMetaData rsmd = rs.getMetaData();
int colCount = rsmd.getColumnCount();
while (rs.next()) {
Element row = doc.createElement("Row");
results.appendChild(row);
for (int ii = 1; ii <= colCount; ii++) {
String columnName = rsmd.getColumnName(ii);
Object value = rs.getObject(ii);
Element node = doc.createElement(columnName);
node.appendChild(doc.createTextNode(value.toString()));
row.appendChild(node);
str = getDocumentAsXml(doc);
catch (Exception e) {
e.printStackTrace();
finally {
try {
if (conn != null) conn.close();
if (s != null) s.close();
if (rs != null) rs.close();
catch (Exception e) {
return str;
public static String getDocumentAsXml(Document doc) throws TransformerConfigurationException, TransformerException
DOMSource domSource = new DOMSource(doc);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
java.io.StringWriter sw = new java.io.StringWriter();
StreamResult sr = new StreamResult(sw);
transformer.transform(domSource, sr);
return sw.toString();
}OutputKeys.OMIT_XML_DECLARATION
-
hi
i am trying to parse a document and change a specific text value within an element althouh when i run the program it changes the nodes text however when i check the xml file it doesnt show the changes it remains the same the code that i am using is as follow iwould be greatful if any one culd help:
// ReplaceText.java
// Reads intro.xml and replaces a text node.
// Java core packages
import java.io.*;
// Java extension packages
import javax.xml.parsers.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;
import javax.xml.transform.dom.*;
// third-party libraries
import org.xml.sax.*;
import org.w3c.dom.*;
public class ReplaceText {
private Document document;
public ReplaceText()
// parse document, find/replace element, output result
try {
// obtain default parser
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
// set parser as validating
factory.setValidating( true );
// obtain object that builds Documents
DocumentBuilder builder = factory.newDocumentBuilder();
// set error handler for validation errors
builder.setErrorHandler( new MyErrorHandler() );
System.err.println( "reading" );
// obtain document object from XML document
File f = new File("D:/Documents and Settings/Administrator/Desktop/xml adv java bk/appC/intro.xml");
System.err.println( "reading" );
document = builder.parse(f);
//document = builder.parse( new File( "intro.xml" ) );
System.err.println( "reading document" );
// retrieve the root node
Node root = document.getDocumentElement();
if ( root.getNodeType() == Node.ELEMENT_NODE ) {
Element myMessageNode = ( Element ) root;
NodeList messageNodes =
myMessageNode.getElementsByTagName( "message5" );
if ( messageNodes.getLength() != 0 ) {
Node message = messageNodes.item( 0 );
System.out.println("iiiii");
// create text node
Text newText = document.createTextNode(
"New Changed Message!!" );
// get old text node
Text oldText =
( Text ) message.getChildNodes().item( 0 );
// replace text
//message.removeChild(oldText);
message.replaceChild( newText, oldText );
// output Document object
// create DOMSource for source XML document
Source xmlSource = new DOMSource( document );
// create StreamResult for transformation result
Result result = new StreamResult( System.out );
// create TransformerFactory
TransformerFactory transformerFactory =
TransformerFactory.newInstance();
// create Transformer for transformation
Transformer transformer =
transformerFactory.newTransformer();
transformer.setOutputProperty( OutputKeys.INDENT, "yes" );
transformer.setOutputProperty( OutputKeys.STANDALONE, "yes" );
// transform and deliver content to client
transformer.transform( xmlSource, result );
// handle exception creating DocumentBuilder
catch ( ParserConfigurationException parserException ) {
parserException.printStackTrace();
// handle exception parsing Document
catch ( SAXException saxException ) {
saxException.printStackTrace();
// handle exception reading/writing data
catch ( IOException ioException ) {
ioException.printStackTrace();
System.exit( 1 );
// handle exception creating TransformerFactory
catch (
TransformerFactoryConfigurationError factoryError ) {
System.err.println( "Error while creating " +
"TransformerFactory" );
factoryError.printStackTrace();
// handle exception transforming document
catch ( TransformerException transformerError ) {
System.err.println( "Error transforming document" );
transformerError.printStackTrace();
public static void main( String args[] )
ReplaceText replace = new ReplaceText();
}the xml file that i am using is as follows:
<?xml version = "1.0"?>
<!-- Fig. 28.10 : intro.xml -->
<!-- Simple introduction to XML markup -->
<!DOCTYPE myMessage [
<!ELEMENT myMessage (message, message5)>
<!ELEMENT message (#PCDATA)>
<!ELEMENT message5 (#PCDATA)>
]>
<myMessage>
<message>welcome to the xml shhhhhushu</message>
<message5>welcome to the xml shhhhhushu</message5>
</myMessage>i would be greatful if some one could please help.....See if the Text 'oldText' actually has any text within it. Sometimes in DOM parsing, you will get something like:
Element
Text (blank)
Text (actual)
Text (blank)Whereas you would expect to receive:
Element
Text (actual)See if that is the case. If yes, modify your logic to iterate through the child text nodes until one with actual text inside of it (getNodeValue()) is found.
- Saish
Maybe you are looking for
-
C2-03 compatible on US mobile networks?
I recently purchased the Nokia C2-03 for a senior staff member since Nokia advertises it as a quad-band phone. GSM 850/900/1800/1900 However the phone does not recognise any sim card inserted in the device when in the US. Is there any setting that ne
-
?
-
How do i get a song to a ring tone on my phone
How do i get a song in i tunes on my phone to a ring tone on my phone?
-
Configuration required in Cat 4006 to forward errors to syslog server
Hi, I have setup a Kiwi syslog server. I want to configure in my Cat 4006 switch to forward the following messages to my syslog server 1. configuration changes 2. Vlan creation /modification 3. Power supply failures/module failures/temperature 4. Whe
-
In PSE 9.0, how do I import images from hard drive files into the organizer without importing duplicated files already in the organizer or How do I find duplicated images within the organizer so that I can delete them?