• Post Reply Bookmark Topic Watch Topic
  • New Topic

Create InputStream from org.w3c.dom.Document

 
Gitahi Ng'ang'a
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi everyone,

I am writing a packing and unpacking routine that converts an object to and from XML for the purpose of sending data (XML) over http. I am using the org.apache.commons.httpclient API. Specifically, I intend to call the setRequestEntity(RequestEntity) method of the PostMethod class. In creating a RequestEntity, I am required to pass an InputStream to the constructor. What I have, however, is only the Document (org.w3c.dom.Document) I get after packing my software object into XML. How can I create an InputStream on the basis of my document object?

Thanks.
 
Greg Charles
Sheriff
Posts: 3010
12
Firefox Browser IntelliJ IDE Java Mac Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First of all, do you know how to create XML from a DOM Document? Basically it's something like this:



OK, so that lets you stream to your output stream, but you said you need an input stream. Well, in theory you could use PipedInputStream and PipedOutputStream to pipe the XML output to the input of your HTTP client. However, that can be tricky to get right. It's really better for interprocess communication and the reading and writing should be happening in different threads. Probably an easier way would be just to stream the XML to a temp file on the file system, or into a byte array in memory and then get an input stream with FileInputStream or ByteArrayInputStream.
 
Paul Clapham
Sheriff
Posts: 21878
36
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It seems to me you should be able to do this with StAX. The first step would be to create an XMLEventReader over the DOM Document:

The next step would be to write a subclass of Reader which would wrap that XMLEventReader. When it was asked to return chars, it would get the next event and convert it to chars. There would be some bookkeeping but it shouldn't be too difficult to get a basic implementation working.
 
Gitahi Ng'ang'a
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Paul and Greg for your answers. I actually found a more straight forward way to send the content of my XML document as part of a HTTP request for my purposes. I just write out the string representation of my document into a URLConnection's OutputStream and voila! I was actually disliking having to use third party libraries so I am happy with this solution.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!