XML - DOM tree - XML
I'm building an application that takes an xml file, turns it into a DOM tree, then the user selects different options from a database to manipulate the internal information gathered by the original XML file, the program is a process and at the end of the process the original XML file has been updated with new information, i need help with finding some code to take the DOM tree information displayed to the user and save back out as a new XML file. any help would be greatly appreciated.
You can use JDOM, Xerces XMLSerializer, or J2SE's Transformer. The first 2 are pretty simple. The 3rd isn't too hard. An example can be found in code sample 3 on http://java.sun.com/developer/technicalArticles/xml/JavaTechandXML_part3/.
Similar Messages
-
Hi
I have an xml document which has the folowing format:
<RESULTS>
<DATA>
<ROWSET>
<ROW ID=1>
<A>1</A>
<B>30100</B>
<C>26380</C>
<D>99999</D>
<E>-311.78</E>
</ROW>
</ROWSET>
</DATA>
<FORMAT>
<ROWSET>
<ROW ID=1>
<A><STYLE>1</STYLE></A>
<B><STYLE>2</STYLE></B>
<C><STYLE>3</STYLE></C>
<D><STYLE>2</STYLE></D>
<E><STYLE>4</STYLE></E>
</ROW>
</ROWSET>
</FORMAT>
<RESULTS>
I now want to merge FORMAT and DATA to produce a new xml. I need to add the STYLE in FORMAT as an attribute to A, B, C, D and E by matching the ROW IDs making the new xml like
<RESULTS>
<DATA>
<ROWSET>
<ROW ID=1>
<A STYLE="1">1</A>
<B STYLE="2">30100</B>
<C STYLE="3">26380</C>
<D STYLE="2">99999</D>
<E STYLE="4">-311.78</E>
</ROW>
</ROWSET>
</DATA>
</RESULTS>
Can some1 come up with how this could be done?Hi I actually want to add 1 of the subtree as an attribute to its corressponding elements in the other tree.
Like in this case:
<RESULTS>
<DATA>
<ROWSET>
<ROW ID=1>
<A>1</A>
<B>30100</B>
<C>26380</C>
<D>99999</D>
<E>-311.78</E>
</ROW>
</ROWSET>
</DATA>
<FORMAT>
<ROWSET>
<ROW ID=1>
<A><STYLE>1</STYLE></A>
<B><STYLE>2</STYLE></B>
<C><STYLE>3</STYLE></C>
<D><STYLE>2</STYLE></D>
<E><STYLE>4</STYLE></E>
</ROW>
</ROWSET>
</FORMAT>
<RESULTS>
STYLE which is a child element of A in FORMAT becomes the attribute of A in DATA. Is there any way to do this? -
Help with creating a new XML file from an existing DOM tree!!
i want to create a new XML file from an existing DOM tree
i used this code to create a new document:
static public Document createDocument(String fileName) throws ParserConfigurationException//,IOException,SAXException
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setIgnoringComments(true);
factory.setIgnoringElementContentWhitespace(true);
factory.setValidating(true);
DocumentBuilder builder =factory.newDocumentBuilder();
return builder.newDocument();
// handle exception creating DocumentBuilder
catch ( ParserConfigurationException parserError ) {
throw new ParserConfigurationException();
}then i used this code to transform the DOM :
public void exportDocument(Document document) {
try {
Source xmlSource = new DOMSource( document );
Result result = new StreamResult( System.out );
TransformerFactory transformerFactory =
TransformerFactory.newInstance();
Transformer transformer =transformerFactory.newTransformer();
transformer.setOutputProperty( "indent", "yes" );
transformer.transform( xmlSource, result );
//then catching the exceptions
But the file was not created and i didn't find where can i specify the DTD that the XML file should use and where can i enter the name of the XML file itself
Another questoin can i write a DTD file dynamically during the execution of the program??Cross-post: http://forum.java.sun.com/thread.jspa?threadID=784467&messageID=4459240#4459240
-
Generate an XML file from a DOM tree
Hi,
I'm trying to generate an XML file from a DOM tree that I obtained from another XML file with the Xerces library. I used the following operation :
public static void writeXmlFile(Document doc, String filename) {
try {
Source source = new DOMSource(doc);
File file = new File(filename);
Result result = new StreamResult(file);
Transformer xformer = TransformerFactory.newInstance().newTransformer();
xformer.transform(source, result);
} catch (TransformerConfigurationException e) {
System.err.println(e);
System.exit(1);
} catch (TransformerException e) {
System.err.println(e);
System.exit(1);
But I have this Windows/Linux problem. When I execute this on Windows, everything is correct. But if I try on Linux (every distribution does the same thing), I obtain an XML file where everything is written on just ONE LINE : there is neither identation nor carriage return at the end of a line ... And that is pretty annoying 'cause I need to SEE what I generate ...
Thanks for your answer,
Blueberryfin.Actually I would think that no indents and no new-lines would be more correct, but maybe it's an option for parsers to do it either way if you don't specify it. If you want to specify it, look at this post from last month:
http://forum.java.sun.com/thread.jsp?forum=34&thread=383400 -
Hello,
I build a DOM tree in my applet.
Then I transform it to XML String.
But since the JRE 1.4.2_05 it doesn't work.
These lines failed because these variables became final:
org.apache.xalan.serialize.CharInfo.XML_ENTITIES_RESOURCE = getClass().getResource("XMLEntities.res").toString();
org.apache.xalan.processor.TransformerFactoryImpl.XSLT_PROPERTIES = getClass().getResource("XSLTInfo.properties").toString();The rest of the code :
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document domXML = builder.newDocument();
// I build my DOM Tree
StringWriter xmlResult = new StringWriter();
Source source = new DOMSource(domXML);
Result result = new StreamResult(xmlResult);
Transformer xformer = TransformerFactory.newInstance().newTransformer();
xformer.setOutputProperty(javax.xml.transform.OutputKeys.INDENT,"yes");
xformer.transform(source,result);Is there any other way to get an XML String from a DOM tree in an applet ?
I'm so disappointed to note this big problem.Does anyone have an idea why I get this error message when try to use transform in an applet?
Thanks...
java.lang.ExceptionInInitializerError
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at org.apache.xalan.serialize.SerializerFactory.getSerializer(Unknown Source)
at org.apache.xalan.transformer.TransformerIdentityImpl.createResultContentHandler(Unknown Source)
at org.apache.xalan.transformer.TransformerIdentityImpl.transform(Unknown Source)
at matrix.CreateMtrx.SaveDoc(CreateMtrx.java:434)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at thinlet.Thinlet.invokeImpl(Unknown Source)
at thinlet.Thinlet.invoke(Unknown Source)
at thinlet.Thinlet.handleMouseEvent(Unknown Source)
at thinlet.Thinlet.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Caused by: java.lang.RuntimeException: The resource [ XMLEntities.res ] could not load: java.net.MalformedURLException: no protocol: XMLEntities.res
XMLEntities.res java.net.MalformedURLException: no protocol: XMLEntities.res
at org.apache.xalan.serialize.CharInfo.<init>(Unknown Source)
at org.apache.xalan.serialize.SerializerToXML.<clinit>(Unknown Source)
... 28 more -
How to convert DOM Tree in XML File
Hi there,
I am successful to build a DOM tree in memory where i am adding elements. Now after all this i want to make a XML file of that DOM representation. Now, i am confused with my code that how to transfer DOM structure to xml file ? A small code is attached herewith ?
doc = db.newDocument();
doc.normalizeDocument();
doc.setXmlVersion("1.0");
doc.createComment("Created By: Sachin Kulkarni");
Element rn = doc.createElement("RootNode");
Element n1 = doc.createElement("A1");
((Node)n1).setNodeValue("Element A1");
Element n11 = doc.createElement("A11");
((Node)n11).setNodeValue("Element A11");
Element n12 = doc.createElement("A12");
((Node)n12).setNodeValue("Element A12");
((Node)n1).appendChild( ((Node)n11) );
((Node)n1).appendChild( ((Node)n12) );
Element n2 = doc.createElement("A2");
((Node)n2).setNodeValue("Element A2");
Element n3 = doc.createElement("A3");
((Node)n3).setNodeValue("Element A3");
((Node)rn).appendChild( ((Node)n1) );
((Node)rn).appendChild( ((Node)n2) );
((Node)rn).appendChild( ((Node)n3) );
//creating the xml file
Source source = new DOMSource((Element) doc.getElementsByTagName("RootNode").item(0));
StringWriter out = new StringWriter();
StreamResult result = new StreamResult(out);
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty("encoding", "iso-8859-1");
transformer.setOutputProperty("indent", "yes");
//transformer.setOutputProperty("test.xml","1");
//transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
transformer.transform(source,result);
result.getWriter().toString();
==================
Is it any problem with the implementation ? How to use fileoutputstream with this ?I have done like this:
DocumentBuilderFactory docBuildFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = docBuildFactory.newDocumentBuilder();
Document doc = builder.newDocument();
Element root = (Element)doc.createElement("Root");
doc.appendChild(root);
Element address = (Element)doc.createElement("Address");
address.appendChild((Element)doc.createElement("Street"));
address.appendChild((Element)doc.createElement("PostCode"));
address.appendChild((Element)doc.createElement("Town"));
Element country = (Element)doc.createElement("Country");
country.setAttribute("type","EU");
Text cname = doc.createTextNode("Spain");
country.appendChild(cname);
address.appendChild(country);
root.appendChild(address);
TransformerFactory tranFactory = TransformerFactory.newInstance();
Transformer aTransformer = tranFactory.newTransformer();
aTransformer.setOutputProperty(OutputKeys.INDENT, "yes");
Source src = new DOMSource(doc);
Result dest = new StreamResult(new FileOutputStream(new File("test.xml")));
aTransformer.transform(src, dest); -
How can i write the DOM tree to the XML File?
Asslamo ala mn etb3a Alhoda.
My problem priefly is that i can't write the DOM tree to XML file.
I write following code to give the user the ability to input the name of data base which he want to create.
If i wrote DB name,its atrributes and its values succefully to XML file ,then i'll read it succefully to RAM.
It'll be simple DBMS.
***My code***
import javax.swing.*;
import javax.xml.parsers.*;
import org.w3c.dom.Document;
import org.w3c.dom.DOMException;
import org.w3c.dom.Element;
public class Main {
* @param args
public static void main(String[] args) {
// TODO Auto-generated method stub
String DBname;
DBname=JOptionPane.showInputDialog("Enter Your Data Base Name");
OPerations O=new OPerations();
O.creatDB(DBname);
class OPerations {
public void creatDB(String name){
//get an empty Document
DocumentBuilderFactory f; f=DocumentBuilderFactory.newInstance();
try {
builder = f.newDocumentBuilder();
Document doc= builder.newDocument();
//Build tree DOM With the root Node
Element root=doc.createElement(name);
//add the root element to thevdocument
doc.appendChild(root);
catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}Do an identity transformation to output it:TransformerFactory tf = TransformerFactory.newInstance();
Transformer tr = tf.newTransformer();
tr.transform(new DOMSource(doc), new StreamResult(new FileOutputStream(new File(filename))));(typed without syntax check) -
XML Parser for Java v2. Applying XSLT to DOM tree
I encountered pretty weird behavior of XML Parser for Java v2.
While applying XSLT to XML document created in memory using DOM
interface I couldn't access element attributes. For example,
given the XML document:
<root>
<Item ID="00001">Value of Item 00001</Item>
<Item ID="00002">Value of Item 00002</Item>
</root>
and XSLT:
<xsl:template match="/">
<HTML>
<HEAD>
<TITLE>XSLT Test</TITLE>
</HEAD>
<BODY>
<xsl:for-each select="/Error">
<H1>Error</H1><xsl:value-of select="."/>
</xsl:for-each>
<TABLE border="0" cellspacing="0" cellpadding="2">
<TBODY>
<xsl:for-each select="/root">
<TR>
<TH style="background-color:khaki">
<xsl:text>Attribute</xsl:text>
</TH>
<TH style="background-color:khaki">
<xsl:text>Value</xsl:text>
</TH>
</TR>
<xsl:for-each select="Item">
<TR>
<TD><xsl:value-of select="@ID"/></TD>
<TD><xsl:value-of select="."/></TD>
</TR>
</xsl:for-each>
</xsl:for-each>
</TBODY>
</TABLE>
</BODY>
</HTML>
</xsl:template>
If I build DOM tree by parsing XML file the resulting HTML
document after applying XSLT will display
Attribute Value
00001 Value of Item 00001
00002 Value of Item 00002
But if I build DOM tree using following code:
XMLDocument xDoc = new XMLDocument();
Element root = xDoc.createElement( "root" );
xDoc.appendChild( root );
Element elem = xDoc.createElement( "Item" );
elem.setAttribute( "ID", "00001" );
root.appendChild( elem ).
appendChild( xDoc.createTextNode( "Value of Item 00001" ) );
elem = xDoc.createElement( "Item" );
elem.setAttribute( "ID", "00002" );
root.appendChild( elem )
.appendChild( xDoc.createTextNode( "Value of Item 00002" ) );
the same XSLT will produce the following HTML output:
Attribute Value
Value of Item 00001
Value of Item 00002
So the value for the ID attribute is not displayed. At the same
time I can access this attribute using DOM interface. For
example, following code
NodeList nList = xDoc.getElementsByTagName( "Item" );
Element e;
for( int i = 0; i < nList.getLength(); i++ )
e = (Element)nList.item( i );
System.out.println( "ID: " + e.getAttribute( "ID" ) );
produces an output
ID: 00001
ID: 00002
Here is the code for applying XSLT to DOM tree:
DOMParser parser = new DOMParser();
parser.parse( new FileInputStream( "test.xsl" ) );
XMLDocument xsldoc = parser.getDocument();
XSLStylesheet xsl = new XSLStylesheet( xsldoc, createURL( "" ) );
XMLDocument out = new XMLDocument();
out.appendChild( new XSLProcessor().processXSL(xsl, xDoc) );
out.print( new FileOutputStream( "test.html" ) );
Andrei Filimonov
nullWe are not getting what you're getting on Solaris. See the
following:
Script started on Tue Jun 22 18:53:56 1999
Processing /view/test/vobs/oracore3/.ndeprodrc.csh
Processing /private/.nderc.csh
[test] > cat bruno.xml
<my_grandpa age="88">
<my_dad age="66">
<me age="44">
<my_son age="22">
</my_son>
</me>
</my_dad>
</my_grandpa>
[test] > cat bruno.xsl
<?xml version="1.0"?>
<!-- Identity transformation -->
<xsl:stylesheet xmlns:xsl="http://www.w3.org/XSL/Transform/1.0">
<xsl:template match="me">
<xsl:value-of select="my_son/@age"/>
<xsl:value-of select="@age"/>
<xsl:value-of select="../@age"/>
<xsl:value-of select="../../@age"/>
</xsl:template>
</xsl:stylesheet>
[test] > java XSLSample bruno.xsl bruno.xml
<root>
22446688
</root>
[test] > exit
script done on Tue Jun 22 18:54:22 1999
What platform are you on and does your stylesheet and xml doc
match ours?
Oracle XML Team
http://technet.oracle.com
Oracle Technology Network
Bruno Bontempi (guest) wrote:
: I had a similar problem in accessing element attributes from
an
: XSLT sheet.
: It seems like the processor correctly accesses element
attributes
: in the context node, but does not retrieve values of
attributes
: outside the context node.
: For example, for an XML document like:
: <my_grandpa age="88">
: <my_dad age="66">
: <me age="44">
: <my_son age="22">
: </my_son>
: </me>
: </my_dad>
: </my_grandpa>
: and an XSL stylesheet like:
: <xsl:template match="me">
: <xsl:value-of select="my_son/@age"/>
: <xsl:value-of select="@age"/>
: <xsl:value-of select="../@age"/>
: <xsl:value-of select="../../@age"/>
: </xsl:template>
: I expect an output like:
: 22446688
: but all I get is
: 44
: I am also using Jim Clark's XT, which is returning the
expected
: result.
: Thanks in advance for your help,
: Bruno.
: Andrei Filimonov (guest) wrote:
: : I encountered pretty weird behavior of XML Parser for Java
v2.
: : While applying XSLT to XML document created in memory using
DOM
: : interface I couldn't access element attributes. For example,
: : given the XML document:
: : <root>
: : <Item ID="00001">Value of Item 00001</Item>
: : <Item ID="00002">Value of Item 00002</Item>
: : </root>
: : and XSLT:
: : <xsl:template match="/">
: : <HTML>
: : <HEAD>
: : <TITLE>XSLT Test</TITLE>
: : </HEAD>
: : <BODY>
: : <xsl:for-each select="/Error">
: : <H1>Error</H1><xsl:value-of select="."/>
: : </xsl:for-each>
: : <TABLE border="0" cellspacing="0" cellpadding="2">
: : <TBODY>
: : <xsl:for-each select="/root">
: : <TR>
: : <TH style="background-color:khaki">
: : <xsl:text>Attribute</xsl:text>
: : </TH>
: : <TH style="background-color:khaki">
: : <xsl:text>Value</xsl:text>
: : </TH>
: : </TR>
: : <xsl:for-each select="Item">
: : <TR>
: : <TD><xsl:value-of select="@ID"/></TD>
: : <TD><xsl:value-of select="."/></TD>
: : </TR>
: : </xsl:for-each>
: : </xsl:for-each>
: : </TBODY>
: : </TABLE>
: : </BODY>
: : </HTML>
: : </xsl:template>
: : If I build DOM tree by parsing XML file the resulting HTML
: : document after applying XSLT will display
: : Attribute Value
: : 00001 Value of Item 00001
: : 00002 Value of Item 00002
: : But if I build DOM tree using following code:
: : XMLDocument xDoc = new XMLDocument();
: : Element root = xDoc.createElement( "root" );
: : xDoc.appendChild( root );
: : Element elem = xDoc.createElement( "Item" );
: : elem.setAttribute( "ID", "00001" );
: : root.appendChild( elem ).
: : appendChild( xDoc.createTextNode( "Value of Item
00001" )
: : elem = xDoc.createElement( "Item" );
: : elem.setAttribute( "ID", "00002" );
: : root.appendChild( elem )
: : .appendChild( xDoc.createTextNode( "Value of Item
00002" )
: : the same XSLT will produce the following HTML output:
: : Attribute Value
: : Value of Item 00001
: : Value of Item 00002
: : So the value for the ID attribute is not displayed. At the
same
: : time I can access this attribute using DOM interface. For
: : example, following code
: : NodeList nList = xDoc.getElementsByTagName( "Item" );
: : Element e;
: : for( int i = 0; i < nList.getLength(); i++ )
: : e = (Element)nList.item( i );
: : System.out.println( "ID: " + e.getAttribute( "ID" ) );
: : produces an output
: : ID: 00001
: : ID: 00002
: : Here is the code for applying XSLT to DOM tree:
: : DOMParser parser = new DOMParser();
: : parser.parse( new FileInputStream( "test.xsl" ) );
: : XMLDocument xsldoc = parser.getDocument();
: : XSLStylesheet xsl = new XSLStylesheet( xsldoc, createURL
: : XMLDocument out = new XMLDocument();
: : out.appendChild( new XSLProcessor().processXSL(xsl, xDoc) );
: : out.print( new FileOutputStream( "test.html" ) );
: : Andrei Filimonov
null -
Hello,
I am trying to generate a XML file from a DOM tree. This facility is there in IBM parser.
But anyone can help me out in generating a XML file or string from a DOM tree using the Crimson parser provided by default in JDK 1.4.0
Thank youThe only way I know is to use JDOM (which provides a output package).
You can build a JDOM tree starting from your DOM tree, and then output this JDOM tree in an XML file.
Hope it will help. -
How i can store a DOM Tree to XML file
I want to insert a xml documet into another another xml document and then store it.
for this i have parsed a xml document using com.sun.xml.parser and got its domtree in document doc1 by builder.getDocument(). After that i parsed another xml document and got it's domtree in document doc2 by builder.getDocument().
now i created a Document type doc . I create dom tree in doc that contains all the nodes of doc1 and insert the doc2 at a position . If i m printing this doc i got the required document. Now i want to store this doc into a xml file. so i paas thid doc and filename in which i want to store it into a function
public static void writeXmlToFile(String filename, Document document)
try
// Prepare the DOM document for writing
Source source = new DOMSource(document);
// Prepare the output file
File file = new File(filename);
Result result = new StreamResult(file);
// Write the DOM document to the file
// Get Transformer
Transformer xformer = TransformerFactory.newInstance().newTransformer();
// Write to a file
xformer.transform(source, result);
catch (TransformerConfigurationException e)
System.out.println("TransformerConfigurationException: " + e);
catch (TransformerException e)
System.out.println("TransformerException: " + e);
but i m getting following error
Exception in thread "main" java.lang.AbstractMethodError: com.sun.xml.tree.ElementNode.getNamespacesURI()Ljava/lang/String;
at com.sun.apache.xalan.internal.xsltc.trax.DOM2TO.parse(Unknown Source)
at com.sun.apache.xalan.internal.xsltc.trax.DOM2TO.parse(Unknown Source)
at com.sun.apache.xalan.internal.xsltc.trax.DOM2TO.parse(Unknown Source)
at com.sun.apache.xalan.internal.xsltc.trax.TranformerImpl.transformIdentity(Unknown Source)
at com.sun.apache.xalan.internal.xsltc.trax.TranformerImpl.transformIdentity(Unknown Source)
at com.sun.apache.xalan.internal.xsltc.trax.TranformerImpl.transformIdentity(Unknown Source)thanks for the reply
i m able to do my job using
import javax.xml.parsers.*;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder1 = factory.newDocumentBuilder();
doc = builder1.parse(uri);
when i want to covert this doc into an xml file by passing this doc in the function below then it is ok..
public static void writeXmlToFile(String filename, Document document)
try
// Prepare the DOM document for writing
Source source = new DOMSource(document);
// Prepare the output file
File file = new File(filename);
Result result = new StreamResult(file);
// Write the DOM document to the file
// Get Transformer
Transformer xformer = TransformerFactory.newInstance().newTransformer();
// Write to a file
xformer.transform(source, result);
catch (TransformerConfigurationException e)
System.out.println("TransformerConfigurationException: " + e);
catch (TransformerException e)
System.out.println("TransformerException: " + e);
but i want to use com.sun.xml.parser like
import com.sun.xml.parser.*;
import com.sun.xml.tree.XmlDocumentBuilder;
XmlDocumentBuilder builder = new XmlDocumentBuilder();
Parser parser = new com.sun.xml.parser.Parser();
parser.setDocumentHandler(builder);
builder.setParser(parser);
builder.setDisableNamespaces(false);
parser.parse(uri);
doc = builder.getDocument();
when i m trying to store this doc into an xml file by passing this doc into funtion writeXmlToFile( filename, doc) then the errors occur (that i hav told in the first post)
plz help.. -
Unparsing a DOM tree and write XML to file
Hi,
I have created a DOM tree from scratch and would like to unparse the DOM tree and write the XML to a file, but how do I do that?
Does anybody got code examples that do this?
All help are very appreciated!
/DanielThank you very much for the hint! Unfortunaly I still got problem to get it work though.
I made a little piece of test code to try it but during the execution of the "Transformer.transform(source,result)" method I gets an "org.w3c.dom.DOMException".
Does anybody see what that problem might be cause of by exmining the code below?
I also would like to know how to specify the location where I would like to print out the XML file.
Here is my little piece of test code:
try{
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFadctory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
doc.appendChild(doc.createElement("topLevel"));
Element elm = doc.getDocumentElement();
elm = (Element)elm.appendChild(doc.createElement("PersonData"));
elm = (Element)elm.appendChild(doc.createElement("Name"));
elm.setAttribute("Firstname","D");
elm.setAttribute("Lastname", "D");
DOMResult result = new DOMResult(doc);
DOMSource source = new DOMSource(doc);
TransformerFactory transformerFactory = TansformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.transform(source,result);
}catch(ParserConfigurationException e) {
}catch(IOException e) {
}catch(TransformerException te) { -
Sizing DOM trees created by Oracle Java XML parser (v2)
Hello,
Has anyone seen/got any formulas that can be used to calculate the DOM tree memory requirements for a given XML document.
My team has developed some software that, acts like an XSLT, and it runs out of memory for bigger documents. I am able to allocate more memory (usuing java -Xmx<larger figure>) to the process but it would be nice to go to my team leader and say that a file of a given structure would require so much memory.
At the moment, we are guessing and using the Runtime.getRuntime().freeMemory() and Runtime.getRuntime().TotalMemory()
to provide some very rough estimates.
XSLTs wouldnt be able to do what we want. If I could give the team leader some figures then he may be able to justify converting the code to use JDOM instead of a DOM tree.
Thanks in Advance.
Mark RobbinsCan you paste your java code here ? I assume, you must have tried type-casting.
-
How to load data from XML DOM into tables using Business Components
<p>
Hi,
</p>
<p>
I need to upload XML file (it's not a problem) an load data (DOM tree) from this file into relationan tables. This filelooks like this:
</p>
<p>
<font face="courier new,courier" size="2"><Departments>
<Department>
<DepartmentName>OPERATIONS</DepartmentName>
<Localization>BOSTON</Localization>
<Employees>
<Employee>
<LastName>TURNER</LastName>
<Job>SALESMAN</Job>
<Manager>7698</Manager>
<HireDate>1981-09-08</HireDate>
<Salary>1500</Salary>
<Commerce>0</Commerce>
</Employee>
</Employees>
</Department>
</Departments></font>
</p>
<p>
Is there any Business Components support to obtain this ? What about primary and foreign keys values (there is no in XML file). How to place this XML data in appropriate tables ?
</p>
<p>
Kuba
</p>Pl post details of exact OS and database versions, along with a sample of the XML file and description of the tables. What have you tried so far ?
http://docs.oracle.com/cd/E11882_01/server.112/e22490/ldr_control_file.htm#i1005614
HTH
Srini -
[Q] convert DOM to XML Document
Hi,
Is there any class or library which convert DOM to XML document?
----- java program ------------
import org.w3c.dom.*;
import org.apache.crimson.tree.XmlDocument;
public class Sample {
public static void main(String args[]) {
// create a document and root element
Document doc = new XmlDocument();
Element root = doc.createElement("html");
doc.appendChild(root);
// append a data
Element body = doc.createElement("body");
root.appendChild(body);
body.appendChild(doc.createTextNode("Hello"));
// convert DOM to XML Document
}----- expected result ----------
<html>
<body>
Hello
</body>
</html>Could you help me?Hi,
Look at the package javax.xml.transform
or
try the following code:
I tried the following code.
----- java program ------------
import javax.xml.parsers.*;
import org.w3c.dom.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import java.io.OutputStream;
public class Sample {
public static void main(String[] args) {
try {
// create a document and root element
Document doc = DocumentBuilderFactory.newInstance()
.newDocumentBuilder()
.newDocument();
Element root = doc.createElement("html");
doc.appendChild(root);
// append a data
Element body = doc.createElement("body");
root.appendChild(body);
body.appendChild(doc.createTextNode("Hello"));
Element ul = doc.createElement("ul");
String[] list = {"foo", "bar", "baz"};
for (int i=0; i<list.length; i++) {
Element li = doc.createElement("li");
li.appendChild(doc.createTextNode(list));
ul.appendChild(li);
body.appendChild(ul);
// convert DOM to XML Document
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
//OutputStream stream = new FileOutputStream("output.xml");
OutputStream stream = System.out;
transformer.transform(new DOMSource(doc), new StreamResult(stream));
} catch (Exception ex) {
ex.printStackTrace();
----- result ------------
<html>
<body>Hello<ul>
<li>foo</li>
<li>bar</li>
<li>baz</li>
</ul>
</body>
</html>Great! Very thanks! -
Question about XML DOM de-bugging.
I have programmed the following class as an excercise in using the DOM and in recursion.
I'm having trouble,however, in debugging my iterate() method.
Sometimes it fails to print certain outer tags.
I'm faily confident there aren't any problems in using entirely static methods in the class.
I simply want it to iterate over all Nodes in the xml document,
and print them to the file in correct order.
Is there anyone out there who could debug my iterate() method?
import org.w3c.dom.*;
import javax.xml.parsers.*;
import java.io.*;
public class DomParsing {
private static PrintStream stream;
public static void main (String [] args)
try
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
File file = new File("cd-catalog.xml");
Node child = null;
Document document = builder.parse(file);
Node element = (Node)document.getDocumentElement();
stream = new PrintStream(new File("SCREEN_OUTPUT.txt"));
iterate(element);
stream.close();
catch (Exception e)
{e.printStackTrace();}
public static void iterate(Node element) //bug in this method.
if(element instanceof Node)
peekNode(element);
peekAttributes(element);
Node [] children = getChildren(element);
if(children instanceof Node[])
for(int i=0;i<children.length;i++)
iterate(children);
element = getSibling(element);
if(element instanceof Node)
iterate(element);
else {
return;}
private static Node [] getChildren(Node element)
Node [] children = null;
if(element.hasChildNodes()){
NodeList nodes= element.getChildNodes();
children = new Node [nodes.getLength()];
for(int i=0;i<nodes.getLength();i++)
{children[i] = nodes.item(i);}
return children;}
private static Node getSibling(Node element)
return element.getNextSibling();}
private static void peekNode(Node node)
if((node instanceof Node) && (stream instanceof PrintStream))
if(node.getNodeName()!=null && (!node.getNodeName().equals("#text")))
{stream.println(new String(node.getNodeName()));
if(node.getNodeValue()!=null)
{stream.println(new String(node.getNodeValue()));
private static void peekAttributes(Node element)
if(element.hasAttributes())
NamedNodeMap map = element.getAttributes();
for(int i=0;i<map.getLength();i++)
Attr attribute = (Attr)map.item(i);
peekNode((Node)attribute);}Never fear, Ihave found my answer!
I had unwitingly disasociated recursive steps,
instead of correctly associated.
The following runs correctly in
all my instances:
import org.w3c.dom.*;
import javax.xml.parsers.*;
import java.io.*;
import java.util.*;
public class DomParsing {
//Main method call to leverage the Iterator Class.
public static void main (String [] args)
Iterator iterator = new Iterator("tomcat-users.xml");
class Iterator {
private LinkedList<String> myDocument;
//private PrintStream stream;
//Constructor accesses xml file for parsing work.
public Iterator (String fileName)
try{
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
File file = new File(fileName);
Node child = null;
Document document = builder.parse(file);
Node element = (Node)document.getDocumentElement();
//stream = new PrintStream(new File("SCREEN_OUTPUT.txt"));
myDocument = new LinkedList<String>();
System.out.println("___________________________________________________");
iterate(element);
//stream.close();
ListIterator<String> nodes = myDocument.listIterator();
while(nodes.hasNext())
System.out.println(nodes.next().trim());
System.out.println("___________________________________________________");
catch (Exception e)
{e.printStackTrace();}
//This method is intended to be called recursively
//to set up a "tree" arrangement in memory
//representing an xml document tree.
private void iterate(Node element) {
if (element == null)
return;
if(element instanceof Node)
peekNode(element);
peekAttributes(element);
Node [] children = getChildren(element);
if(children instanceof Node[])
for(int i=0;i<children.length;i++)
iterate(children);
Node sibling = getSibling(element);
if(sibling instanceof Node)
{iterate(sibling);}
//Returns array of all Children Nodes of an Element.
private Node [] getChildren(Node element)
Node [] children = null;
if(element.hasChildNodes()){
NodeList nodes= element.getChildNodes();
children = new Node [nodes.getLength()];
for(int i=0;i<nodes.getLength();i++)
{children[i] = nodes.item(i);}
return children;}
//Obtains the next Sibling element
private Node getSibling(Node element)
return element.getNextSibling();}
//These print any Node and any data,
//from Element,attribute,attribute values,
//sibling,child, etc..
private void peekNode(Node node)
if((node instanceof Node))// && (stream instanceof PrintStream))
if(node.getNodeName()!=null && (!node.getNodeName().equals("#text")))
{//stream.println(new String(node.getNodeName().trim()));
myDocument.add(node.getNodeName().trim());
//System.out.println(node.getNodeName().toString());
if(node.getNodeValue()!=null)
{//stream.println(new String(node.getNodeValue().trim()));
myDocument.add(node.getNodeValue().trim());
//System.out.println(node.getNodeValue().toString());
//This examines the xml attributes on and element node.
private void peekAttributes(Node element)
if(element.hasAttributes())
NamedNodeMap map = element.getAttributes();
for(int i=0;i<map.getLength();i++)
Attr attribute = (Attr)map.item(i);
peekNode((Node)attribute);}
Maybe you are looking for
-
Icloud is not working on my mac
Hi, Im having problems with my icloud - my mac will not play the music I have uploaded. This is the first time it has happened, and I have used icloud for months (maybe a year now). Any help ?
-
Enabling East Asian/Non-latin alphabet support?
Hi guys. Very new here, this will be my first post Been using Arch for a few days now and this only just occurred to me. How exactly do I go about installing East Asian language support on my system? I'm assuming it's a really simple install from a r
-
IPad DocumentsToGo and Dock conector to VGA-Adapter
Hi there, I just bought an iPad two weeks ago and last week the VGA Adapter. The clear intention was to show some PowerPoint slides with the iPad using a projector. I tried using the iPad with a Samsung 23" LCD-Monitor at home before. It worked fine,
-
Having just rented CCand Lightroom and found that some filters available on CS5 are not on CC, Artistic and Sketch for example. Is this correct
-
Please Help: Unknown BlackBerry user-agent
I have been trying to download a mobile program designed just for Blackberrys. The web address begins with http://blackberry. After I enter the address, I get the following error message: Unknown blackberry user-agent Mozilla5.0 (blackberry; U;