Transform Java object to XML string object

M

Matt

I want to know if there are Java API to convert
Java objects to XML string? I want to transform
the form data in JSP page to XML string. I have a
schema file, but I don't want to do it manually.
I know Java classes XMLEncoder, XML Decoder can do the
similar job, but it just output to output stream, not to a string object.

any ideas?? Thanks!!
 
M

mromarkhan

Peace be unto you.

Solution: ByteArrayOutputStream

Output:
<?xml version="1.0" encoding="UTF-8"?>
<java version="1.4.2_04" class="java.beans.XMLDecoder">
<object class="javax.swing.JTree">
<void property="cellRenderer">
<void property="text">
<string>jsdk1.5</string>
</void>
</void>
</object>
</java>

<code>
import java.beans.XMLEncoder;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.JTree;
import java.awt.BorderLayout;
import java.io.IOException;
import java.io.ByteArrayOutputStream;
public class XMLEncodeJTree
{
JTree jtree;
public XMLEncodeJTree()
{
DefaultMutableTreeNode root =
new DefaultMutableTreeNode("C Drive");
DefaultMutableTreeNode java =
new DefaultMutableTreeNode("jsdk1.5");
root.add(new DefaultMutableTreeNode("My Documents"));
root.add(new DefaultMutableTreeNode("WINDOWS"));
root.add(java);
java.add(new DefaultMutableTreeNode("Bin"));
java.add(new DefaultMutableTreeNode("Lib"));
jtree = new JTree(root);
ByteArrayOutputStream jtreestring = new ByteArrayOutputStream();
XMLEncoder en = new XMLEncoder(jtreestring);
en.writeObject(jtree);
en.close();
System.out.println(jtreestring.toString());
}
public static void main(String [] s)
{
new XMLEncodeJTree();
}
}
</code>

There is also StringReader and StringWriter
<code>
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.BufferedWriter;
import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.FileReader;
import javax.xml.transform.Source;
import javax.xml.transform.Result;
import org.w3c.dom.Document;
import org.w3c.dom.DOMException;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Attr;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.util.StringTokenizer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.io.FileOutputStream;
import java.io_OutputStreamWriter;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.net.Socket;
import java.net.InetAddress;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.io.StringReader;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import java.awt.BorderLayout;
import javax.swing.text.EditorKit;
import javax.swing.JScrollPane;
public class JNewsReader extends JFrame
{
public static void main(String [] s) throws Exception
{
new JNewsReader();
}
public JNewsReader() throws Exception
{
String inLine = null;
String outLine = null;
String hostname = "news-read3.maxwell.syr.edu";
Socket socket = new Socket(InetAddress.getByName(hostname),119);
BufferedWriter sendOutToSocket = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "US-ASCII"));
BufferedReader readInFromSocket = new BufferedReader(new InputStreamReader( socket.getInputStream(),"US-ASCII"));
inLine = readInFromSocket.readLine(); // read server status line
inLine = null;
outLine = "GROUP comp.lang.java.programmer"; // set group
sendOutToSocket.write(outLine,0,outLine.length());
sendOutToSocket.newLine();
sendOutToSocket.flush();
inLine = readInFromSocket.readLine(); // read server status line
StringTokenizer tokens = new StringTokenizer(inLine); // parse to obtain first article number and last article number
int messageResponse = Integer.parseInt(tokens.nextToken());// and number of messages
int numberOfArticles = Integer.parseInt(tokens.nextToken());
int minimumArticleNumber = Integer.parseInt(tokens.nextToken());
int maximumArticleNumber = Integer.parseInt(tokens.nextToken());
inLine = null;
StringBuffer rawNNTP = new StringBuffer();
for(int articleNumber = maximumArticleNumber - 25;articleNumber <= maximumArticleNumber;articleNumber++)
{
//System.out.print("\r("
//+articleNumber + "/" + maximumArticleNumber
//+ ")");
outLine = "ARTICLE "+articleNumber;// get article
sendOutToSocket.write(outLine,0,outLine.length());
sendOutToSocket.newLine();
sendOutToSocket.flush();
inLine = readInFromSocket.readLine();// read server status
rawNNTP.append(inLine + "\n");
StringTokenizer articleResponseTokens = new StringTokenizer(inLine);
if(articleResponseTokens.nextToken().equals("423")) // 423 no such article number in this group
{
continue;
}
while(true)// write until encounter a line with a single period
{
inLine = null;
inLine = readInFromSocket.readLine();
if(inLine != null)
{
rawNNTP.append(inLine + "\n");
if(inLine.equals("."))
{
break;
}
}
else
{
break;
}
}
}



DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

Pattern pattern = Pattern.compile("[\\x00-\\x1F\\x7F&&[^\\x0A\\x0D\\x09]]");
Matcher matcher = null;
matcher = pattern.matcher(rawNNTP.toString());
String rawNNTPwo = matcher.replaceAll("");

String [] rawNntpArray = rawNNTPwo.split("\n");
Document document;
try
{
DocumentBuilder builder = factory.newDocumentBuilder();
document = builder.newDocument();
Element root = document.createElement("nntpMessages");
document.appendChild(root);
int linecounter = 0;
while(linecounter < rawNntpArray.length)
{
StringTokenizer st;// read header
inLine = null;
inLine = rawNntpArray[linecounter];
linecounter++;
//System.out.println(inLine);
if(inLine == null)
{
break;
}
st = new StringTokenizer(inLine);
String nextToken = st.nextToken();
if(nextToken==null)
{
break;
}
if(nextToken.equals("423"))
{
continue;
}
if(!nextToken.equals("220"))
{
break;
}
Element message = document.createElement("message");
root.appendChild(message);
Element head = document.createElement("head");
message.appendChild(head);
Element body = document.createElement("body");
message.appendChild(body);
Attr serverMsgId = document.createAttribute("serverId");
serverMsgId.setValue(st.nextToken());
message.setAttributeNode(serverMsgId);// read header
String headName = "";
StringBuffer headValue = new StringBuffer();
boolean multiLine = false;
Element unknown;
while(linecounter < rawNntpArray.length)
{
inLine = null;
inLine = rawNntpArray[linecounter];
linecounter++;
//System.out.println(inLine);
if(inLine.equals(""))
{
if(multiLine)
{
unknown = document.createElement(headName);
unknown.appendChild(document.createTextNode(headValue.toString()));
head.appendChild(unknown);
}
break;
}

if(inLine.charAt(0)==' ' || inLine.charAt(0) == '\t')// multiline
{
multiLine=true;
headValue.append(inLine.trim());
continue;
}
else// not multiline
{
multiLine=false;
int colonIndex = inLine.indexOf(':'); // to handle hand coded messages
if(colonIndex == -1)
{
break;
}
headName = inLine.substring(0,colonIndex);
headName = headName.replace('-','_');
headValue.append(inLine.substring(colonIndex+2));
}
unknown = document.createElement(headName);
unknown.appendChild(document.createTextNode(headValue.toString()));
head.appendChild(unknown);
headName = "";
headValue.setLength(0);
}
StringBuffer bodyBuffer = new StringBuffer();//read body
while(linecounter < rawNntpArray.length)
{
inLine = null;
inLine = rawNntpArray[linecounter];
//System.out.println(inLine);
linecounter++;
if(inLine.equals("."))
{
break;
}
bodyBuffer.append(inLine+"\n");
}
// do pattern match for http or www. space on both ends
// pre attach <raw><a></raw> not <textnode>
//body.appendChild(document.createTextNode("More to come<br />"));
body.appendChild(document.createTextNode(bodyBuffer.toString()));
}

// thread
// find all references
NodeList references= document.getElementsByTagName("References");
// go through them all
// connecting them to message id
/*if(references== null)
{
continue;
}*/
for(int i = 0;i < references.getLength();i++ )
{
// get node
Node refNode = references.item(i);
if(refNode == null)
{
//System.out.println("refNode is null");
continue;
}
Node firstChild = refNode.getFirstChild();
if(firstChild == null)
{
//System.out.println("firstChild is null");
continue;
}
//get value text is a node
String refNodeValue = firstChild.getNodeValue();
// parse last message id
if(refNodeValue == null)
{
//System.out.println("refNodeValue is null");
continue;
}
//System.out.println(refNodeValue);
StringTokenizer refNodeValueTokens = new StringTokenizer(refNodeValue);
String refId = "";
// get last refid
while(refNodeValueTokens.hasMoreTokens())
{
refId = refNodeValueTokens.nextToken();
}
// search and connect
// get all message ids
NodeList msgidlist= document.getElementsByTagName("Message_ID");
if(msgidlist == null)
{
//System.out.println("Msgid list is null");
continue;
}
// go through all of them to see if match
for(int j = 0;j < msgidlist.getLength();j++ )
{
// get node
Node msgidNode = msgidlist.item(j);
//get value
String msgid = msgidNode.getFirstChild().getNodeValue();
if(msgid.equals(refId))
{
//System.out.println("Found a winner!"+msgid);
// attach then break at first occurence
// get parent of reference = head
// get parent of head = message
Node refNodeMessage = refNode.getParentNode().getParentNode();
// create new node reply to store message
Element reply = document.createElement("reply");
reply.appendChild(refNodeMessage);
// attach reply to end of mesg->
Node originalNodeMessage = msgidNode.getParentNode().getParentNode();
originalNodeMessage.appendChild(reply);
break;
}
}
}

//System.out.println("Finish threading");

StringWriter stringWriter = new StringWriter();
StringReader stringReader = new StringReader(getXslSource());

Source xMLSource = new DOMSource(document);
Source xSLSource = new StreamSource(stringReader);
Result result = new StreamResult(stringWriter);
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer(xSLSource);
transformer.transform(xMLSource,result);
System.out.println(stringWriter.toString());
//Gui
// References Message-ID: <[email protected]>
JEditorPane jep = new JEditorPane();
jep.setEditable(false);
jep.setContentType("text/html");
EditorKit kit = jep.getEditorKit();
javax.swing.text.Document doc = kit.createDefaultDocument();
// References Message-ID: <[email protected]>
doc.putProperty( "IgnoreCharsetDirective", Boolean.TRUE );
kit.read(new StringReader(stringWriter.toString()), doc, 0);
jep.setDocument(doc);
this.setTitle("JNewsReader 1.0");
this.getContentPane().add(new JScrollPane(jep),BorderLayout.CENTER);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(512,342);// hypercard
this.setVisible(true);
}
catch(TransformerException te)
{
te.printStackTrace();
}
catch (ParserConfigurationException pce)
{
pce.printStackTrace();
}

}

public String getXslSource()
{
String xsl = "<?xml version = \"1.0\" encoding=\"UTF-8\"?>"+
"<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">"+
"<xsl:eek:utput method=\"html\" omit-xml-declaration=\"yes\" "+
"indent=\"yes\" "+
" />"+
"<xsl:template match=\"/nntpMessages\">"+
"<html lang=\"en\">"+
"<head>"+
"<title>NNTP Client</title>"+
"</head>"+
"<body>"+
"<xsl:apply-templates select=\"message\"/>"+
"</body>"+
"</html>"+
"</xsl:template>"+
"<xsl:template match=\"message\">"+
"<xsl:apply-templates select=\"head\" />"+
"<xsl:apply-templates select=\"body\" />"+
"<xsl:apply-templates select=\"reply\" />"+
"</xsl:template>"+
"<xsl:template match=\"head\">"+
"<a id=\"id{parent::*/attribute::serverId}\"></a>"+
"<div class=\"thehead\">"+
"<xsl:text>Subject: </xsl:text><span style=\"font-size:130%;\"><xsl:value-of select=\"Subject\" /></span><br />"+
"</div>"+
"</xsl:template>"+
"<xsl:template match=\"head2\">"+
"<a id=\"id{parent::*/attribute::serverId}\"></a>"+
"<div class=\"thehead\">"+
"<xsl:text>Subject: </xsl:text><span style=\"font-size:120%;\"><xsl:value-of select=\"Subject\" /></span><br />"+
"<xsl:text>From: </xsl:text><xsl:value-of select=\"From\" /><br />"+
"<xsl:text>Date: </xsl:text><xsl:value-of select=\"Date\" /><br />"+
"<xsl:text>Newsgroup: </xsl:text><xsl:value-of select=\"Newsgroup\" /><br />"+
"<xsl:text>Message-ID: </xsl:text><xsl:value-of select=\"Message_ID\" /><br />"+
"<xsl:text>References: </xsl:text><xsl:value-of select=\"References\" /><br />"+
"<xsl:text>Lines: </xsl:text><xsl:value-of select=\"Lines\" />"+
"</div>"+
"</xsl:template>"+
"<xsl:template match=\"body\">"+
"<div class=\"thebody\">"+
"<pre>"+
"<xsl:value-of select=\".\" />"+
"</pre>"+
" <a href=\"#id{parent::*/attribute::serverId}\">Top</a>"+
" </div>"+
" </xsl:template>"+
"<xsl:template match=\"reply\">"+
"<div class=\"reply\">"+
"<xsl:apply-templates select=\"message\"/>"+
"</div>"+
"</xsl:template>"+
"</xsl:stylesheet>";
return xsl;
}
}
</code>

Have a good day.
 
D

Dave Monroe

I want to know if there are Java API to convert
Java objects to XML string? I want to transform
the form data in JSP page to XML string. I have a
schema file, but I don't want to do it manually.
I know Java classes XMLEncoder, XML Decoder can do the
similar job, but it just output to output stream, not to a string object.

any ideas?? Thanks!!

SOAP is the ticket.

Check out http://www.ws-i.org or http://www.apache.org.

The current buzz phrase is 'web services'.
 
V

Vijayakumar Ranganathan

Hi All,
According to me you go for JAXB for transforming Java Objects to XML
Stream. I feel that API is available on Java Webservice Development
Kit. Its really very easy to implement. Its done based on the
Schema/DTD of the XML. More details look into java.sun.com spec's.
Regards
Vijay


Peace be unto you.

Solution: ByteArrayOutputStream

Output:
<?xml version="1.0" encoding="UTF-8"?>
<java version="1.4.2_04" class="java.beans.XMLDecoder">
<object class="javax.swing.JTree">
<void property="cellRenderer">
<void property="text">
<string>jsdk1.5</string>
</void>
</void>
</object>
</java>

<code>
import java.beans.XMLEncoder;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.JTree;
import java.awt.BorderLayout;
import java.io.IOException;
import java.io.ByteArrayOutputStream;
public class XMLEncodeJTree
{
JTree jtree;
public XMLEncodeJTree()
{
DefaultMutableTreeNode root =
new DefaultMutableTreeNode("C Drive");
DefaultMutableTreeNode java =
new DefaultMutableTreeNode("jsdk1.5");
root.add(new DefaultMutableTreeNode("My Documents"));
root.add(new DefaultMutableTreeNode("WINDOWS"));
root.add(java);
java.add(new DefaultMutableTreeNode("Bin"));
java.add(new DefaultMutableTreeNode("Lib"));
jtree = new JTree(root);
ByteArrayOutputStream jtreestring = new ByteArrayOutputStream();
XMLEncoder en = new XMLEncoder(jtreestring);
en.writeObject(jtree);
en.close();
System.out.println(jtreestring.toString());
}
public static void main(String [] s)
{
new XMLEncodeJTree();
}
}
</code>

There is also StringReader and StringWriter
<code>
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.BufferedWriter;
import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.FileReader;
import javax.xml.transform.Source;
import javax.xml.transform.Result;
import org.w3c.dom.Document;
import org.w3c.dom.DOMException;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Attr;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.util.StringTokenizer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.io.FileOutputStream;
import java.io_OutputStreamWriter;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.net.Socket;
import java.net.InetAddress;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.io.StringReader;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import java.awt.BorderLayout;
import javax.swing.text.EditorKit;
import javax.swing.JScrollPane;
public class JNewsReader extends JFrame
{
public static void main(String [] s) throws Exception
{
new JNewsReader();
}
public JNewsReader() throws Exception
{
String inLine = null;
String outLine = null;
String hostname = "news-read3.maxwell.syr.edu";
Socket socket = new Socket(InetAddress.getByName(hostname),119);
BufferedWriter sendOutToSocket = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "US-ASCII"));
BufferedReader readInFromSocket = new BufferedReader(new InputStreamReader( socket.getInputStream(),"US-ASCII"));
inLine = readInFromSocket.readLine(); // read server status line
inLine = null;
outLine = "GROUP comp.lang.java.programmer"; // set group
sendOutToSocket.write(outLine,0,outLine.length());
sendOutToSocket.newLine();
sendOutToSocket.flush();
inLine = readInFromSocket.readLine(); // read server status line
StringTokenizer tokens = new StringTokenizer(inLine); // parse to obtain first article number and last article number
int messageResponse = Integer.parseInt(tokens.nextToken());// and number of messages
int numberOfArticles = Integer.parseInt(tokens.nextToken());
int minimumArticleNumber = Integer.parseInt(tokens.nextToken());
int maximumArticleNumber = Integer.parseInt(tokens.nextToken());
inLine = null;
StringBuffer rawNNTP = new StringBuffer();
for(int articleNumber = maximumArticleNumber - 25;articleNumber <= maximumArticleNumber;articleNumber++)
{
//System.out.print("\r("
//+articleNumber + "/" + maximumArticleNumber
//+ ")");
outLine = "ARTICLE "+articleNumber;// get article
sendOutToSocket.write(outLine,0,outLine.length());
sendOutToSocket.newLine();
sendOutToSocket.flush();
inLine = readInFromSocket.readLine();// read server status
rawNNTP.append(inLine + "\n");
StringTokenizer articleResponseTokens = new StringTokenizer(inLine);
if(articleResponseTokens.nextToken().equals("423")) // 423 no such article number in this group
{
continue;
}
while(true)// write until encounter a line with a single period
{
inLine = null;
inLine = readInFromSocket.readLine();
if(inLine != null)
{
rawNNTP.append(inLine + "\n");
if(inLine.equals("."))
{
break;
}
}
else
{
break;
}
}
}



DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

Pattern pattern = Pattern.compile("[\\x00-\\x1F\\x7F&&[^\\x0A\\x0D\\x09]]");
Matcher matcher = null;
matcher = pattern.matcher(rawNNTP.toString());
String rawNNTPwo = matcher.replaceAll("");

String [] rawNntpArray = rawNNTPwo.split("\n");
Document document;
try
{
DocumentBuilder builder = factory.newDocumentBuilder();
document = builder.newDocument();
Element root = document.createElement("nntpMessages");
document.appendChild(root);
int linecounter = 0;
while(linecounter < rawNntpArray.length)
{
StringTokenizer st;// read header
inLine = null;
inLine = rawNntpArray[linecounter];
linecounter++;
//System.out.println(inLine);
if(inLine == null)
{
break;
}
st = new StringTokenizer(inLine);
String nextToken = st.nextToken();
if(nextToken==null)
{
break;
}
if(nextToken.equals("423"))
{
continue;
}
if(!nextToken.equals("220"))
{
break;
}
Element message = document.createElement("message");
root.appendChild(message);
Element head = document.createElement("head");
message.appendChild(head);
Element body = document.createElement("body");
message.appendChild(body);
Attr serverMsgId = document.createAttribute("serverId");
serverMsgId.setValue(st.nextToken());
message.setAttributeNode(serverMsgId);// read header
String headName = "";
StringBuffer headValue = new StringBuffer();
boolean multiLine = false;
Element unknown;
while(linecounter < rawNntpArray.length)
{
inLine = null;
inLine = rawNntpArray[linecounter];
linecounter++;
//System.out.println(inLine);
if(inLine.equals(""))
{
if(multiLine)
{
unknown = document.createElement(headName);
unknown.appendChild(document.createTextNode(headValue.toString()));
head.appendChild(unknown);
}
break;
}

if(inLine.charAt(0)==' ' || inLine.charAt(0) == '\t')// multiline
{
multiLine=true;
headValue.append(inLine.trim());
continue;
}
else// not multiline
{
multiLine=false;
int colonIndex = inLine.indexOf(':'); // to handle hand coded messages
if(colonIndex == -1)
{
break;
}
headName = inLine.substring(0,colonIndex);
headName = headName.replace('-','_');
headValue.append(inLine.substring(colonIndex+2));
}
unknown = document.createElement(headName);
unknown.appendChild(document.createTextNode(headValue.toString()));
head.appendChild(unknown);
headName = "";
headValue.setLength(0);
}
StringBuffer bodyBuffer = new StringBuffer();//read body
while(linecounter < rawNntpArray.length)
{
inLine = null;
inLine = rawNntpArray[linecounter];
//System.out.println(inLine);
linecounter++;
if(inLine.equals("."))
{
break;
}
bodyBuffer.append(inLine+"\n");
}
// do pattern match for http or www. space on both ends
// pre attach <raw><a></raw> not <textnode>
//body.appendChild(document.createTextNode("More to come<br />"));
body.appendChild(document.createTextNode(bodyBuffer.toString()));
}

// thread
// find all references
NodeList references= document.getElementsByTagName("References");
// go through them all
// connecting them to message id
/*if(references== null)
{
continue;
}*/
for(int i = 0;i < references.getLength();i++ )
{
// get node
Node refNode = references.item(i);
if(refNode == null)
{
//System.out.println("refNode is null");
continue;
}
Node firstChild = refNode.getFirstChild();
if(firstChild == null)
{
//System.out.println("firstChild is null");
continue;
}
//get value text is a node
String refNodeValue = firstChild.getNodeValue();
// parse last message id
if(refNodeValue == null)
{
//System.out.println("refNodeValue is null");
continue;
}
//System.out.println(refNodeValue);
StringTokenizer refNodeValueTokens = new StringTokenizer(refNodeValue);
String refId = "";
// get last refid
while(refNodeValueTokens.hasMoreTokens())
{
refId = refNodeValueTokens.nextToken();
}
// search and connect
// get all message ids
NodeList msgidlist= document.getElementsByTagName("Message_ID");
if(msgidlist == null)
{
//System.out.println("Msgid list is null");
continue;
}
// go through all of them to see if match
for(int j = 0;j < msgidlist.getLength();j++ )
{
// get node
Node msgidNode = msgidlist.item(j);
//get value
String msgid = msgidNode.getFirstChild().getNodeValue();
if(msgid.equals(refId))
{
//System.out.println("Found a winner!"+msgid);
// attach then break at first occurence
// get parent of reference = head
// get parent of head = message
Node refNodeMessage = refNode.getParentNode().getParentNode();
// create new node reply to store message
Element reply = document.createElement("reply");
reply.appendChild(refNodeMessage);
// attach reply to end of mesg->
Node originalNodeMessage = msgidNode.getParentNode().getParentNode();
originalNodeMessage.appendChild(reply);
break;
}
}
}

//System.out.println("Finish threading");

StringWriter stringWriter = new StringWriter();
StringReader stringReader = new StringReader(getXslSource());

Source xMLSource = new DOMSource(document);
Source xSLSource = new StreamSource(stringReader);
Result result = new StreamResult(stringWriter);
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer(xSLSource);
transformer.transform(xMLSource,result);
System.out.println(stringWriter.toString());
//Gui
// References Message-ID: <[email protected]>
JEditorPane jep = new JEditorPane();
jep.setEditable(false);
jep.setContentType("text/html");
EditorKit kit = jep.getEditorKit();
javax.swing.text.Document doc = kit.createDefaultDocument();
// References Message-ID: <[email protected]>
doc.putProperty( "IgnoreCharsetDirective", Boolean.TRUE );
kit.read(new StringReader(stringWriter.toString()), doc, 0);
jep.setDocument(doc);
this.setTitle("JNewsReader 1.0");
this.getContentPane().add(new JScrollPane(jep),BorderLayout.CENTER);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(512,342);// hypercard
this.setVisible(true);
}
catch(TransformerException te)
{
te.printStackTrace();
}
catch (ParserConfigurationException pce)
{
pce.printStackTrace();
}

}

public String getXslSource()
{
String xsl = "<?xml version = \"1.0\" encoding=\"UTF-8\"?>"+
"<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">"+
"<xsl:eek:utput method=\"html\" omit-xml-declaration=\"yes\" "+
"indent=\"yes\" "+
" />"+
"<xsl:template match=\"/nntpMessages\">"+
"<html lang=\"en\">"+
"<head>"+
"<title>NNTP Client</title>"+
"</head>"+
"<body>"+
"<xsl:apply-templates select=\"message\"/>"+
"</body>"+
"</html>"+
"</xsl:template>"+
"<xsl:template match=\"message\">"+
"<xsl:apply-templates select=\"head\" />"+
"<xsl:apply-templates select=\"body\" />"+
"<xsl:apply-templates select=\"reply\" />"+
"</xsl:template>"+
"<xsl:template match=\"head\">"+
"<a id=\"id{parent::*/attribute::serverId}\"></a>"+
"<div class=\"thehead\">"+
"<xsl:text>Subject: </xsl:text><span style=\"font-size:130%;\"><xsl:value-of select=\"Subject\" /></span><br />"+
"</div>"+
"</xsl:template>"+
"<xsl:template match=\"head2\">"+
"<a id=\"id{parent::*/attribute::serverId}\"></a>"+
"<div class=\"thehead\">"+
"<xsl:text>Subject: </xsl:text><span style=\"font-size:120%;\"><xsl:value-of select=\"Subject\" /></span><br />"+
"<xsl:text>From: </xsl:text><xsl:value-of select=\"From\" /><br />"+
"<xsl:text>Date: </xsl:text><xsl:value-of select=\"Date\" /><br />"+
"<xsl:text>Newsgroup: </xsl:text><xsl:value-of select=\"Newsgroup\" /><br />"+
"<xsl:text>Message-ID: </xsl:text><xsl:value-of select=\"Message_ID\" /><br />"+
"<xsl:text>References: </xsl:text><xsl:value-of select=\"References\" /><br />"+
"<xsl:text>Lines: </xsl:text><xsl:value-of select=\"Lines\" />"+
"</div>"+
"</xsl:template>"+
"<xsl:template match=\"body\">"+
"<div class=\"thebody\">"+
"<pre>"+
"<xsl:value-of select=\".\" />"+
"</pre>"+
" <a href=\"#id{parent::*/attribute::serverId}\">Top</a>"+
" </div>"+
" </xsl:template>"+
"<xsl:template match=\"reply\">"+
"<div class=\"reply\">"+
"<xsl:apply-templates select=\"message\"/>"+
"</div>"+
"</xsl:template>"+
"</xsl:stylesheet>";
return xsl;
}
}
</code>

Have a good day.
 
A

Andrew Thompson

M

mromarkhan

Peace be unto you

If your using jaxb, try:

Marshaller m = jc.createMarshaller();
StringWriter stringWriter = new StringWriter();
StreamResult result = new StreamResult( stringWriter );
m.marshal( purchaseOrderForm, result );
String content = stringWriter.toString();

Have a good day.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top