How to transform DOM into String

Hi,
Can any one provide an example of transforming DOM into String using TransformationFactory or any other API of JAXP?
Regards...
Shamit

And for finer output:
      * Prints a textual representation of a DOM object into a text string..
      * @param document DOM object to parse.
      * @return String representation of <i>document</i>.
    static public String toString(Document document) {
        String result = null;
        if (document != null) {
            StringWriter strWtr = new StringWriter();
            StreamResult strResult = new StreamResult(strWtr);
            TransformerFactory tfac = TransformerFactory.newInstance();
            try {
                Transformer t = tfac.newTransformer();
                t.setOutputProperty(OutputKeys.ENCODING, "iso-8859-1");
                t.setOutputProperty(OutputKeys.INDENT, "yes");
                t.setOutputProperty(OutputKeys.METHOD, "xml"); //xml, html, text
                t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
                t.transform(new DOMSource(document.getDocumentElement()), strResult);
            } catch (Exception e) {
                System.err.println("XML.toString(Document): " + e);
            result = strResult.getWriter().toString();
        return result;
    }//toString()

Similar Messages

  • How to convert byte into string

    can any tell me how to convert byte into string
    when im an debugging thid code in eclipse it shows the result in integer format instead of string but in command prompt it is showing result in string format..........plz help
    package str;
    import java.io.*;
    public class Testfile {
    public static void main(String rags[])
    byte b[]=new byte[100];
    try{
    FileInputStream file=new FileInputStream("abc.txt");
    file.read(b,0,50);
    catch(Exception e)
         System.out.println("Exception is:"+e);
    System.out.println(b);
    String str=new String(b);
    System.out.println(str);
    }

    Namrata.Kakkar wrote:
    errors: count cannot be resolved and Unhandled exception type Unsupported Encoding Exception.
    If i write an integer value instead of "count" then Unhandled exception type Unsupported Encoding Exception error is left.This is elementary. You need to go back to [http://java.sun.com/docs/books/tutorial/|http://java.sun.com/docs/books/tutorial/] .

  • How to Parse XML into String in BPEL?

    Hi,
    Can anyone tell me, how can I parse XML into String?
    I am taking input from File Adapter, File adapter is reading that XML.
    Then in assign activity i am using XPath expression(built functions) using XMLParser(),doTranslateToNative() etc.. many functions I have tried but XML is not getting parsed into String Variable.
    Please help me asap.
    Thanks
    Shikha

    Thanks a lot Eric.
    I am trying this, oraext:get-content-as-string('receiveInput_Read_InputVariable','body','/ns3:orders')
    but getting this error
    <bpelFault><faultType>0</faultType><subLanguageExecutionFault xmlns="http://schemas.oracle.com/bpel/extension"><part name="summary"><summary>XPath expression failed to execute. An error occurs while processing the XPath expression; the expression is oraext:get-content-as-string('receiveInput_Read_InputVariable','body','/ns3:orders'). The XPath expression failed to execute; the reason was: internal xpath error. Check the detailed root cause described in the exception message text and verify that the XPath query is correct. </summary></part><part name="code"><code>XPathExecutionError</code></part></subLanguageExecutionFault></bpelFault>

  • How to convert filenames into strings

    im listing a lists of files
    using the method listFiles() which returns me data of type File which are actually
    all files in the dir.
    may i know how do i convert the filenames returned to become strings
    so that i can manipulate the filenames as string format instead of file format?
    thanks for any help suggested!

    Im encountering a problem now before i can test the method...
    This the current problem i had :
    i only showed part of the codes here:
    File[] listing = Dir.listFiles();
    String[] lists;
    for (int i=0; i < listing.length; i++)
    lists[i] = new String(listing.getName());
    out.print(lists[i] + "<br>");
    The error i had:
    variable lists might not have been initialized
    lists[i] = new String(listing[i].getName());
    ^
    1 error
    I forgot how to deal with String array...
    I declare as String[] lists; coz i do not know the size of the array...
    how do i assign the filenames to strings?
    Please kindly help..thanks a lot!

  • How To Convert XML into String?

    Hi,
    I have a requirement in which I need to convert the data from XML file to string.
    E.g.
       <Drawing>
          <DrawingSpecification>
             <Header>
                <SoldTo>SDN</SoldTo>
                <SoldToName>SAP</SoldToName>
                <Date/>
                <Manager>CEO</Manager>
                < Plant>INDIA</Name>
                <Items>
                   <Item>
                       < MaterialNumber>MatNum12</ MaterialNumber>
                       <ProductNumber>ProName12</ ProductNumber>
                   </Item>
               </Items>
               < ClientId>ClientID123</ ClientId>
               <FileName>FileName123</FileName>
               <Type/>
               < TemplateName/>
          </DrawingSpecification>
          <Image contentType=""/>
       < /Drawing>
    Output should be like:
       < File>
          < Content> SDN SAP CEO INDIA MatNum12 ProName12 ClientID123 FileName123</Content>
       < /File>
    Please provide solution for the same.
    Thanks,
    Abhishek.

    what about something like this
    package test;
    import java.io.File;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import org.w3c.dom.Document;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    public class Test {
         public static void main(String args[]) throws Exception {
              DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
              DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
              Document doc = docBuilder.parse(new File("test.xml"));
              StringBuffer buffer = new StringBuffer();
              appendChildren(buffer, doc.getChildNodes());
              System.out.println(buffer.toString());
         private static void appendChildren(StringBuffer buffer, NodeList list) {
              for (int i = 0; i < list.getLength(); i++) {
                   Node node = list.item(i);
                   if (node.getNodeValue() != null) {
                        if (node.getNodeValue().trim().length() > 0) {
                             buffer.append(node.getNodeValue()).append("|");
                   appendChildren(buffer, node.getChildNodes());
    ...btw: IMHO the use of this forum is to get an answer to an particular question - not to ask for complete solutions - create the solution yourself an ask if you are stuck somewhere (with a bit of research (google) it is not hard to find a solution for your problem)
    regards franz
    ...close thread if question is answered

  • How to convert Objext[] into String[] or any other object

    Hi,
    I've happened to come across a weird problem in java 1.6. I am sure it was alright before. Here is what I want to do and the result is
    Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
        Vector toVec = new Vector();
        StringTokenizer addrs = new StringTokenizer(addressesTo,";");
        while(addrs.hasMoreTokens()) {
            toVec.add(new String(addrs.nextToken()));
    String[] to;
    Object[] obj = toVec.toArray();
    to = (String[])obj;
    the tokenizer has at least 1 item. I am sure of it.
    Can anybody explain this phenomena?
    Thanks.

    No, you did not use identical code before, or if you did, you got the same results.
    String[] str[] = (String[])list.toArray(); // won't work, as toArray() returns Object[]
    String[] str[] = (String[])list.toArray(new String[0]); // works, creates a new String[]
    String[] str[] = (String[])list.toArray(newString[list.size()]); // works, returns a reference to the array created inline

  • How to convert BLOB into a String

    Hi,
    I got a blob column from the database.
    It contains one XML File.
    How to convert it into String.
    I need the code for how to convert the blob into String
    Thanks in Advance.

    A blob would be a byte-array, which you can use in the String(byte[]) constructor

  • I want to convert two image files into strings and than to compare them. This is easy, but how to mention where the difference exist?

    I have two image file in bmp file format. How to convert them into string and to check if they are differnt or same. If different how to mention or find that where the difference exists. This idea have to be extented with video application as well.

    Hi,
    if you have vision, you could use the functin IMAQ Image to Array to have a 2D array of the pixel values.
    You can then compare pixel by pixel; if your images come from a camera, I would recommend to set a treshold of acceptance.
    This is a time consuming solution anyway.
    Alternative methods:
    1) Make a subtraction of the two images, the resulting image will be the difference of them
    2 ) Use IMAQ LogDiff function (operators palette)
    3) Calculate the histogram of both image and compare the histogram reports
    Good luck,
    Alberto

  • Transform versions into masters

    How to transform versions into masters ? is it using reprocess masters ? cos I select the image and press that n it stated nothing can be reprocess.
    since i export the version the file size is too small compare to the masters one, could any one help me with this please
    thxxx
    Message was edited by: william7939

    When you go to file>export, there are options to to choose any size and or quality you want. Master files can be exported by going to File in the top left, choose Export from the drop down list, then Master. From the next drop down, select were you want them to go. Then click Export Masters, in the bottom right corner. Done.
    You do the same with versions but there are a lot of options for file size etc. Allan

  • How to convert xslt file into string

    i'm writting a java program to use xslt to transform the xml file. i'm encountering the problem when i try to convert the xslt file into string. i've defined my utility class called 'XmlUtil' to carry out the operation of transform xml file through xslt. but in my main java program i need to convert both xml and xslt file into a string in order to input them in my function argument. my function argument is as follows:
    String htmlString = XmlUtil.applyXsltString(xmlContent, xsltString);
    i've already converted xmlcontent into string by using:
    xmlContent = xmlContentBuffer.toString();
    but i don't know how to convert 'xsltString' now ? i've searched the google for an hour but i cannot find the solution. anyone can help ?
    detail of my souce code is as follow:
    import java.io.*;
    import java.net.*;
    import java.lang.*;
    import java.io.StringReader;
    import java.lang.reflect.Array;
    import java.util.Properties;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.sax.SAXResult;
    import javax.xml.transform.sax.SAXSource;
    import javax.xml.transform.sax.SAXTransformerFactory;
    import javax.xml.transform.sax.TransformerHandler;
    import javax.xml.transform.stream.StreamSource;
    import org.apache.xml.serializer.OutputPropertiesFactory;
    import org.apache.xml.serializer.Serializer;
    import org.apache.xml.serializer.SerializerFactory;
    import org.w3c.dom.Document;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import org.xml.sax.InputSource;
    import org.xml.sax.XMLReader;
    import org.xml.sax.helpers.XMLReaderFactory;
    import XmlUtil;
    public class FileDownload {
    public static void download(String address, String localFileName){
    OutputStream out = null;
    URLConnection conn = null;
    InputStream in = null;
    StringBuffer xmlContentBuffer = new StringBuffer();
    String temp = new String();
    String xmlContent;
    try {
    URL url = new URL(address);
    out = new BufferedOutputStream(
    new FileOutputStream(localFileName));
    conn = url.openConnection();
    in = conn.getInputStream();
    byte[] buffer = new byte[1024];
    int numRead;
    long numWritten = 0;
    System.out.println (in.toString ());
    while ((numRead = in.read(buffer)) != -1) {
    out.write(buffer, 0, numRead);
    numWritten += numRead;
    temp = new String(buffer);
    xmlContentBuffer.append(temp);
    System.out.println(localFileName + "\t" + numWritten);
    xmlContent = xmlContentBuffer.toString();
    String htmlString = XmlUtil.applyXsltString(xmlContent, xsltString);
    } catch (Exception exception) {
    exception.printStackTrace();
    } finally {
    try {
    if (in != null) {
    in.close();
    if (out != null) {
    out.close();
    } catch (IOException ioe) {
    public static void download(String address) {
    int lastSlashIndex = address.lastIndexOf('/');
    if (lastSlashIndex >= 0 &&
    lastSlashIndex < address.length() - 1) {
    download(address, address.substring(lastSlashIndex + 1));
    } else {
    System.err.println("Could not figure out local file name for " + address);
    public static void main(String[] args) {
    for (int i = 0; i < args.length; i++) {
    download(args);
    }

    I don't understand why you need load the XML and XLS files into a String. A Transformer can be constructed from a Source and there is a StreamSouce which can be constructed from an InputStream. The transform() method can take a Source as input and can produce a Result. There is no need to go near a String representation of either the input.

  • How can I send multiple string commands into a VISA write?

    Hi Fellow LabVIEW users
    I am very new to LabVIEW (2.5 months) so please forgive me if my lingo is not up to par.
    How can I send multiple string commands to a VISA write. For example each string command looks like this
    1) 3A00 0000 0000 FFFF FFFF FFFF 0000 0000 FF00 0000 0000 0000 0000 0033 (Scenario 1)
    2) 3A01 0000 0000 FFFF FFFF FFFF 0000 0000 FF00 0000 0000 0000 0000 0034 (Scenario 2)
    3) 3A01 0000 0000 33FF FFFF FFFF 0000 0000 FF00 0000 0000 0000 0000 0067 (Scenario 3).
    and so on and so forth. And there are a number of scenarios.
    Each String scenario will give a different string output which will be interpreted differently in the front panel.
    Right now I have to manually change the string commands on the front panel to give me the desired output. How can I do this without manually changing the commands i.e. hard coding each scenario into the block diagram?
    Thanks, any feedback will help.
    mhaque

    Please stick to your original post.

  • How do I copy the string portion of an enum into the string portion of a cluster?

    I want to do this for the an entire array of clusters.  I'm trying to use a for loop.  Can't figure out how to parse the string portion of the enum into the string portion of the cluster.
    Alternatively, I'd be happy if I could figure out some way to tie the enum to the array of clusters, but I figure that gets problematic.
    DH
    Solved!
    Go to Solution.

    Dark Hollow wrote:
    OK, let's say that the enumerated type has N elements.  I want to initialize an N element array of strings.  How do I reference each string in the enumerated type to get to each string?
    Easy way to do this is to use GetNumericInfo.vi, part of the Variant library, found in vi.lib\utility\VariantDataType\GetNumericInfo.vi.  Wire your enumeration to the Variant input; one of the outputs is an array of the strings in the enumerated type.
    The more complicated way is a for loop, in which you typecast the iterator terminal value to the enumerated type, then use Format Value.  You can get the maximum value of the enumeration by casting 0 to the enumerated type, then decrementing; cast that back to a numeric and add one to get the right value to wire to the N terminal.
    EDIT: just thought I'd add, since RavensFan's reply popped up while I was writing mine - I don't like the Strings[] approach because it doesn't work on RT targets, and I lost a lot of time once due to this trying to figure out why my code wouldn't run properly on an RT system but worked great on my development computer.

  • How to get an xml string into a Document w/o escaping mark-up characters?

    Hi,
    I am using one of the latest xerces using Java. I am pretty sure I am using xerces-2.
    I have an existing Document and I am trying to add more content to it. The new content itself is xml string. I am trying to insert this xml string into the document using document.createTextNode. I am able to insert, but somewhere it is escaping the mark-up characters (<,>,etc). When I convert the document into String, I can see, for example, <userData> instead of <userData>.
    There is an alternative option to accomplish this by creating a new document with this xml string, get the root element, import this element into my document. Execution time for this procedure is very high - means, this is very bad in terms of time-wise performance.
    Can any help on how to accomplish this (bringing an xml string into a document without escaping mark-up characters) in time-efficient way.

    So you want to treat the contents of the string as XML rather than as text? Then you have to parse it.
    Or if your reason for asking is just that you don't like the look of escaped text, then use a CDATA section to contain the text.

  • How to convert BLOB data into string format.

    Hi,
    I have problem while converting blob data into string format.
    for example,
    Select dbms_lob.substr(c.shape.Get_wkb(),4000,1) from geotable c
    will get me the first 4000 byte of BLOB .
    When i using SQL as i did above,the max length is 4000, but i can get 32K using plsql as below:
    declare
    my_var CLOB;
    BEGIN
    for x in (Select X from T)
    loop
    my_var:=dbms_lob.substr(x.X,32767,1)
    end loop
    return my_var;
    I comfortably convert 32k BLOB field to string.
    My problem is how to convert blob to varchar having size more than 32K.
    Please help me to resolve this,
    Thanx in advance for the support,
    Nilesh

    Nilesh,
    . . . .The result of get_wkb() will not be human readable (all values are encoded into some binary format).
    SELECT utl_raw.cast_to_varchar2(tbl.geometry.get_wkt()) from FeatureTable tbl;
    -- resulting string:
        ☺AW(⌂özßHAA
    Å\(÷. . . .You may also want to have a look at { dbms_lob | http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14258/d_lob.htm#i1015792 } "The DBMS_LOB package provides subprograms to operate on BLOBs, CLOBs, NCLOBs, BFILEs, and temporary LOBs."
    Regards,
    Noel

  • How do I Display a string from a servlet into a JSP Page???? NEED HELP!!!!

    Hi guys,
    How do I Display a string from a servlet into a JSP Page...
    Ive tried so many bloody things!.....
    Simply.
    I get text from JSP. The servlet does what ever it does to the string.
    Now. Ive create sessions and bean things,.... how the hell do I display it in a text box... I can display on the screen.. but not in the text box.!!!
    please help!!!

    hmmm, I dont really like using JSP programming, u should be using JAVA..
    the way to do it is:
    Call and cast to the bean like this:
    <%@ page import="beans.*" %>
    <% //cast to bean get request create object
    userNameBean u= (userNameBean) request.getSession().getAttribute("userNameBean");
    then... all you do is call it like this:
    <input type="text" name="firstName" value="<%= u != null? u.getFirstName(): "" %>">
    this is the real programmers way,,,
    chet.~

Maybe you are looking for

  • Quick doubt.. from cursor vairable how to get into page vairable

    Hello i am creating an apex page where i have 2 regions. From the Top region stores all fields entered into the bottom region Text fields like first name and last name and address fields are in region 2(bottom).After region 2, i have a add person but

  • Popup notification in user decision not showing

    Hello, I'm facing a problem with my workflows, I have two workflows in my system, bot are sending user decision to the users, the problem is my requirement is to raise a popup notification once the decision is sent. I have configured the activity to

  • Calling Java Function with Return as String []

    Hi, I have written the following code. It's not compiling OK. DECLARE TYPE Tokens_Type IS VARYING ARRAY(20) OF VARCHAR2(20); s1 Tokens_Type DEFAULT NULL; SQL_STR VARCHAR2(2000) DEFAULT NULL; BEGIN SQL_STR := 'CREATE OR REPLACE FUNCTION Schema1.SPLIT_

  • Anyone have any bugs or fixes in health app?

    My previous weeks data has now gone from my dashboard. It will let me add an item to the dashboard but as soon as I go to the dashboard to view it, it says dashboard is empty.  This only seems to have happened since I linked MY FITNESS PAL app in the

  • How to run JSP in Tomcat

    Hi i am new to java web application, i am running JSP(edited in notepad) in tomcat <html> <head> <title>first jsp page</title> </head> <body> <%! String st = "shyam your JSP Code" %> Welcome ::<%= st %> </body> </html> i saved this jsp as first.jsp a