tags:

views:

343

answers:

3

How can we insert a record into an XML file using Java?

How can we display one record from this XML file using HTML?

+2  A: 

XML to HTML : use XSLT http://www.rgagnon.com/javadetails/java-0407.html inserting another Node in a XML tree: * use the DOM API and node.appendChild(newnode) : http://www.javazoom.net/services/newsletter/xmlgeneration.html * if your tree is too large, use the SAX API

Pierre
+4  A: 

To display a record of html from xml, its called XSLT, which is a stylesheet language for XML,its a way to transform an xml file to display as html, you can use things like Dreamweaver to help you edit and make the transformation.

As oppose to in java; DOM parser loads the XML file into the memory and makes an object model of it. Here is a quick Example on how you can do that.

TStamper
+1  A: 

This code snippet may clarify things for you using XSLT and Java (JSTL), just complementing the good links Pierre and TStamper provided you

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/xml" prefix="x" %>

<c:set var="xslDoc">
    <?xml version="1.0"?>
    <xsl:stylesheet version="1.0"
      xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt;
     <xsl:template match="/">
       <html>
       <body>
      <h2>My CD Collection</h2>
      <table border="1">
        <tr bgcolor="#9acd32">
       <th>Title</th>
       <th>Artist</th>
        </tr>
        <xsl:for-each select="catalog/cd">
       <tr>
         <td><xsl:value-of select="title"/></td>
         <td><xsl:value-of select="artist"/></td>
       </tr>
        </xsl:for-each>
      </table>
       </body>
       </html>
     </xsl:template>
    </xsl:stylesheet>
</c:set>

<c:set var="xmlDoc">
    <?xml version="1.0"?>
    <catalog>
        <cd>
            <title>Stop</title>
            <artist>Sam Brown</artist>
            <country>UK</country>
            <company>A and M</company>
            <price>8.90</price>
            <year>1988</year>
        </cd>
        <cd>
            <title>Red</title>
            <artist>The Communards</artist>
            <country>UK</country>
            <company>London</company>
            <price>7.80</price>
            <year>1987</year>
        </cd>
    </catalog>
</c:set>

<x:transform xml="${xmlDoc}" xslt="${xslDoc}" />

Also, there are many technologies for making this in a servlet or a business class, I like Apache Xalan

victor hugo