DOM tree for HTML
Hello,
How can I create DOM tree for HTML pages with java.
Can anybody tell me about good examples or relevant material for this.
Thanks
Tabbasum
JTidy. Rhino.
Similar Messages
-
Applescript Help: Search for text in Safari DOM tree
Im trying to make a script really similar what was asked here: Re: Find text in webpage and email notification applescript/automator Except instead of searching the "source code" of the page, I want the script to search the "DOM tree" for the page.
To summarize, I am trying to make a script that loads a safari page, searches for a particular text in the DOM Tree, and if found will send me an email.
Here is the code from the other thread I referenced:
on idle
set pagURL to "http://page.url.com?whatever"
if application "Safari" is not running then
quit
return
end if
tell application "Safari"
set URL of document 1 of window 1 to "http://your.web.address/"
delay 5
-- delay to let page load.
if source of document 1 of window 1 contains "search text" then
my sendAMail()
end if
return 900 --fifteen minutes
end tell
end idle
on sendAMail()
tell application "Mail"
set theMess to make new outgoing message at end with properties {sender:"your name", subject:"some subject line", content:"The message you want to send to yourself", visible:true}
tell theMess
make new to recipient at end of to recipients with properties {address:"[email protected]"}
end tell
-- send theMess
end tell
end sendAMail
Any help would be appreciated!For the URL you quote as an example (http://www.sislands.com/coin70/week2/NestedLoops1.htm), using text instead of source worked for me:
if text of document 1 of window 1 contains "1 2 3 4" then
another example:
if text of document 1 of window 1 contains "10 12 14 16" then
Note a double space between single digits (1 2 3 4) and a single space between double digits (10 12 14 16) is required for a match as per the table format:
Any full line:
if text of document 1 of window 1 contains "for (i = 1; i <= 10; i++) { // when i = 10" then
or partial line works:
if text of document 1 of window 1 contains "; i++) { // when i = 10" then -
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 -
Getting HTML string out of DOM tree
after i apply XSL transformation to an XML document, i get a
DOM tree as a result.
how do i extract the HTML from that tree as a string? lotus xsl
lets you pass a PrintWriter to XSLProcessor -- how can I use the
DocumentFragment for that same thing?
thank you very much,
zak.
nullzak may (guest) wrote:
: : At this point we do not support xsl:output so you the only
way
: : to get printed output at this point is to use the DOM print
: : method. xsl:output will be supported in a future release.
: that's great -- but which "DOM print method" are you reffering
: to?
: neither DocumentFragment, nor Document, nor Node have a print
: method.
: my question remains -- how do I get at the HTML result of an
XSL
: transformation? XSLProcessor.processXSL returns a
: DocumentFragment -- how do I print that DocumentFragment,
markup
: tags and all?
: thank you very much,
: zak.
Both XMLDocument and XMLNode have a variety of print methods.
None of them will transform XML into HTML however.
Oracle XML Team
http://technet.oracle.com
Oracle Technology Network
null -
Once I build a DOM tree, how can I write the xml to a string or a file using
the JAXP API. Given any particular Parser implementation, I have been able
to find methods that allow me to write the xml. However, from the java api
(JAXP), there doesn't seem to be a mechanism for doing this. Please
advise...
regards,
toddHi Todd,
You can't write XML out using JAXP 1.0 -- that feature is not included in
the API.
But you can use the XML serialization package that is included in the
built-in parser and the bundled Apache Xerces parser. Check out the
weblogic.apache.xml.serialize, org.apache.xml.serialize packages. The
javadocs are at
http://www.weblogic.com/docs60/xerces/org/apache/xml/serialize/package-summa
ry.html
Cheers,
-Todd
"Todd Singleton" <[email protected]> wrote in message
news:3a2d5bdb$[email protected]..
Once I build a DOM tree, how can I write the xml to a string or a fileusing
the JAXP API. Given any particular Parser implementation, I have beenable
to find methods that allow me to write the xml. However, from the javaapi
(JAXP), there doesn't seem to be a mechanism for doing this. Please
advise...
regards,
todd -
How to modify a node value in a DOM tree?
I have following code; it parses a XML file from a file and builds a in-memory DOM tree, but when I tries to modify one of the node value, it keeps telling me: oracle.xml.parser.v2.XMLDOMException: Node cannot be modified. How do I do it?
// ==================================
DOMParser theParser = new DOMParser();
theParser.setValidationMode(false);
InputStream theInputStream = myApp.class.getResourceAsStream("/test.xml");
theParser.parse(theInputStream);
XMLDocument theXMLDoc = theParser.getDocument();
NodeList theNodeList = theXMLDoc.selectNodes("/root/child");
for (int i = 0; i < theNodeList.getLength(); i++)
theNodeList.item(i).setNodeValue("test");
nullYou're trying to set the node value of an element, which cannot have a node value.
You need to set the node value of the text-node child of the element instead.
Or remove the current text-node child and append a new text-node child with the new value. -
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 -
How to display an xml file as a tree in html
Hi, JAVA/XML/XSLT/HTML gurus,
I have an xml file and want to display it as a tree in html using XSLT.
Is there any example for this?
King regards,
AG... except for the "using XSLT" part. But that doesn't make sense anyway because XSLT doesn't display anything, it just transforms data.
-
Schema validation error when validating dom tree in memory
Hello folks,
I have the following problem:
I construct a xml-file via the DOM API and before writing to file, I want to validate the DOM tree against a existing schema file.
But I always receive following error:
In line 0 of buffer:
LSX-00006: No default namespace for "conf_file"
Validation failed, error 6
Here's what the xml file looks like:
<conf_file xmlns="http://www.sun.com/gridware/configuration_file_format" >
<conf_version>0</conf_version>
<conf_entry>
<param>test</param>
<value>0</value>
</conf_entry>
</conf_file>
The curious thing about that is, when first writing the DOM tree to file via printStream() and then validating the written xml file againstr the schema everything works fine.
Do you know what I doing wrong ?
Thanks ...
HartiIt is a bug.
-
Getting the absolute text position from a DOM tree
Does anybody knows how to get the absolute text position of a node inside the DOM tree? Is there any DOM implementation that keep track of the absolute text position of each Node element or I need to overload somo methods by hand?
Regards,
Daniel OliveiraThe position() function in XSLT returns the order of the element.
For an xml document with elements:
<a>
<b></b>
<b></b>
</a>
<xsl:apply-templates select="b"/>
<xsl:template match="b">
Element b:
<xsl:value-of select="position()"/>
</xsl:template> -
Serialization of DOM Tree+calling POST method in servlet
Hi all,
I am trying to serialize a DOM tree and send it from an applet to a servlet..I am having difficulty in calling the post method of the servlet..can anyone please tell me how the POST method in the servlet is called from the applet...I am using the code as seen on the forum for calling the POST method as below:
URL url = new URL("http://localhost:8080/3awebapp/updateservlet");
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setUseCaches(false);
con.setRequestProperty("Content-Type","application/octet-stream");
System.out.println("Connected");
con.setDoOutput(true);
con.setRequestMethod("POST");
System.out.println("do output called");
con.setDoInput(true);
System.out.println("do Input called");
ObjectOutputStream objout = new ObjectOutputStream(con.getOutputStream());
yet the post method in the servlet does not seem to be called....
another problem I had was trying to serialize a DOM document and send it to the servlet. I am using the following code to write the DOM document on an output stream..would this work:
OutputFormat format = new OutputFormat(document);
XMLSerializer serializer = new XMLSerializer( objout, format );
System.out.println("XML Serializer Started");
DOMSerializer newSerializer=serializer.asDOMSerializer();
newSerializer.serialize( document );
objout.flush();
objout.close();
...since the doPost method of the servlet is not being called I do not whether the above code would be sent to the servlet..
Any advice on the above two matters would be highly appreciated..
Fenilperhaps my piece of code may help You - relevant parts marked //<--,
but I have a problem when reading my object - which is a serialized DomTree :
Variant 1 : sending XML-data as string will arrive as should be, but parser says org.xml.sax.SAXParseException (missing root-element)
Variant 2 : readObject says java.io.OptionalDataException, but the DomTree will be parsed and displayed
-- snipp --
import java.io.InputStream;
import org.w3c.dom.Document;
import java.net.*;
import com.oreilly.servlet.HttpMessage; //<--
import java.util.*;
import java.io.ObjectInputStream;
myApplet :
try {
URL url = new URL(getCodeBase(),"../../xml/FetchDocument");
HttpMessage msg = new HttpMessage(url);
Properties props = new Properties();
props.put("InputFeldName","FeldWert");
InputStream in = msg.sendGetMessage(props);
//<-- alt : sendPostMessage
ObjectInputStream result = new ObjectInputStream(in);
try {
Object obj = result.readObject();
myServlet :
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException, IOException {
TreeCreator currentTree = new TreeCreator();
ObjectOutputStream out = new ObjectOutputStream(res.getOutputStream());
-- variant 1 :
out.writeObject(currentTree.skillOutputString());
out.flush();
out.close();
-- variant 2 :
OutputFormat( TreeCreator.cdi ); //Serialize DOM
OutputFormat format = new OutputFormat( currentTree.getCDI() ); format.setEncoding("ISO-8859-1");
XMLSerializer serial = new XMLSerializer( out, format );
serial.asDOMSerializer(); // As a DOM Serializer
serial.serialize( currentTree.getCDI().getDocumentElement() );
serial.endDocument();
out.flush();
out.close(); -
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.. -
Conceptual problem: AJAX Memory tree for navigation
Hello,
I have a conceptual problem with a navigation tree.
I have to implement a AJAX memory tree for navigation purposes, which should be on page 0, so this tree is on the left side of every page.
Therefore I searches some examples and found this: http://www.oracle.com/technology/pub/articles/spendolini-tree.html
So I try to rebuild this example with my custom tables and recognised that this example is very slow. I have round about 100 nodes in the tree and my database and network connection is extremly fast(I`m sitting in a proffesional data center).
So first of all I am wondering why the tree is so slow when I try to expand it and if it is possible to use this tree on the page 0.
Because of the performance problem I searched for some alternatives, but I didn`t found one.
Every custom APEX-tree is not dynamic(AJAX) and the dynamic APEX-lists can not base on a select-statement.
So at this moment I don`t know how to build a AJAX memory tree for navigation which is fast, looks good and works as expected.
Does anybody have an idea why the tree is so slow?
Are there alternatives which I can try to use?
Thank you,
TimHi Tim
100 nodes is not a lot of data for a tree, so why bother with AJAX at all.
Just render the entire tree, and let the user expand and collapse nodes as they like.
APEX has a dhtml tree in the standard themes which is enough to get you started.
The issue I had with it is that it isn't stateful, so doesn't remember which nodes are open between page refreshes.
That's what got me into ExtJS originally.
If you look at my demo, I have a couple of examples worth looking at:
- [tree using APEX lists|http://apex.oracle.com/pls/otn/f?p=200801:2025:0::NO:::] uses APEX built in hierarchical lists, which allows conditional logic on nodes
- [AJAX editable tree|http://apex.oracle.com/pls/otn/f?p=200801:2013:0::NO:::] which is fully AJAX enabled.
The other point worth mentioning is if you are using hierarchical queries for your tree you should consider restructuring your data set.
Typically trees are fairly static, in that the data changes very little over time.
This makes a very strong case for maintaining the node sequence and level in a denormalised way.
Data updates become more expensive, but read operations, which will be the bulk of your operations will be very fast.
Many choices on how to implement, e.g. materialized views with refresh on demand.
Regards
Mark
[Random Insights into Oracle|http://oracleinsights.blogspot.com/] | [Marks Playpen|http://apex.oracle.com/pls/otn/f?p=200801] -
How to Recursively traverse a Dom Tree
Hi there, I'm new to java and xml and would like to see some sample code on recursively traversing a DOM tree in java, printing out all Element, Text, etc to the console window.
Please helpUse this: DomRead.java at your own risk. caveat: this gets screwed up if the attributes are multi-valued. You can use XPath to get around that. I am struggling with the proper XPath expressions.
import org.xml.sax.*;
import org.w3c.dom.*;
import java.util.*;
* version 1.0
public class DomRead implements ErrorHandler
private static final String CRLF = System.getProperty("line.separator");
private static String key = "";
private static String value = "";
private Hashtable elements = new Hashtable();
* This constructor has to be used to pass in the DOM document which needs to
* be read so that this class can generate the hashtable with the attributes as
* keys and their corresponding values.
public DomRead(Document rootDoc)
process(rootDoc);
private void processChild(NodeList root)
for(int i=0;i<root.getLength(); i++)
process(root.item(i));
private void printAttrib(Node root)
NamedNodeMap attrib = root.getAttributes();
int len = attrib.getLength();
if(len == 0) return;
for(int i=0; i < len ; i++)
Attr attribute = (Attr) attrib.item(i);
key = attribute.getNodeValue();
private void process(Node root)
switch( root.getNodeType())
case Node.DOCUMENT_NODE :
Document doc = (Document) root;
processChild(doc.getChildNodes());
break;
case Node.ELEMENT_NODE :
root.setNodeValue(root.getNodeValue() );
printAttrib(root);
processChild(root.getChildNodes());
break;
case Node.TEXT_NODE :
Text text = (Text) root;
value = text.getNodeValue().trim();
//Log("Value: "+value+CRLF);
if(!value.equalsIgnoreCase(""))
elements.put(key, value);
break;
* Use this method, if you intend to print out the contents of the generated
* hashtable.
public void printElements()
for (Enumeration enum = elements.keys(); enum.hasMoreElements() ;)
String tKey = (String)enum.nextElement();
Log(tKey+"::::"+(String)elements.get(tKey));
* This method returns the Hashtable with the attributes that have non-empty
* values.
public Hashtable getElements()
return elements;
public void error(SAXParseException e)
e.printStackTrace();
public void warning(SAXParseException e)
e.toString();
public void fatalError(SAXParseException e)
e.printStackTrace();
private static void Log(String log)
System.out.print(log+CRLF);
} -
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) {
Maybe you are looking for
-
What wrong of my below java program? Please teach me to edit it!
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class CustomPanel extends JPanel implements ActionListener public final static int WIDTH =30, HEIGHT =30, X_RANGE =260, Y_RANGE =165; private Button bt1=new Button ("square"); p
-
HT1495 When I try to open iTunes on my PC it it's locked and won't open?
When I try to open iTunes on my PC it it's locked and won't open?
-
PM 6.5 won't open - get messsage chunkmgr.lib PM 6.5 was upgraded on line - can't just reinstall Help, Pat P
-
Please help on how Bex execute the query designed in query designer.
Hi All, Want to know how bex execute/interpret the query when the query is execute in analyzer. I mean which part of the query is executed first, like filter,RKF or CKF etc. Want to do step by step analysis .Please suggest on this. Thanks & Regards
-
What is Applecare saying about RSD?
Now that the RSD problem was acknowledged by Apple, and that they are telling people to call Applecare if it happens, can someone tell us what they are saying when you call? Thx.