DOM to String

Hi,
I want to transform a xml document (org.w3c.dom.Document) into a String. I use Trax to do it, but it doesn?t work very well. The method I use for the transformation is the folowing one:
public String toString()
try
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
DOMSource source = new DOMSource(mDocument);
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
transformer.transform(source, result);
return sw.toString();
catch (Exception e) {
System.out.println("Error in method toString: "+e.getMessage());
return null;
When I use this method to transform, for example, the next document:
<?xml version="1.0" encoding="UTF-8">
<Message><C&oacute;digo>3</C&oacute;digo></Message>
I get the next String:
<?xml version="1.0" encoding="UTF-8">
<Message><C&#number;digo>3</C#&number;digo></Message>
| |
| |
243 243
when I would like to get a String like:
<?xml version="1.0" encoding="UTF-8">
<Message><C�digo>3</C�digo></Message>
What I'm doing bad?

I think so. I'm going to explain you what the 'program' (sorry, yesterday I wrote 'application' instead of 'program') do exactly.
1) There is an applet which write a XML operation message that is sended to a servlet. For example:
<?xml version="1.0" encoding="UTF-8"?>
<Message><C&oacute;digo>2</C&oacute;digo></Message>
2) The servlet recives the message, and get 'C&oacute;digo' which is used to write a database query.
3) Once the servlet gets the results of the query, the servlet writes another XML message with the results of the query, and send it to the applet.
<?xml version="1.0" encoding="UTF-8"?>
<Message><C&oacute;digo>2</C&oacute;digo><Result>...</Result></Message>
4) The applet receives the XML response message, and transformate it into a String, but the string is:
<?xml version="1.0" encoding="UTF-8"?>
<Message><C&#243;digo>2</C&#243;digo><Result>...</Result></Message>
If I use the next code with the message received by the applet, I get 'c&oacute;digo':
Node vMessageNode = mDocument.getDocumentElement();
Node vCodeNode = vMessageNode.getFirstChild();
String vCode = vMessageNode.getNodeName();
But if I use the method toString (I wrote it yesterday) to convert the whole message into a string, the string contains "&#243;", when I'd like that it had "&oacute".
What is very strange is that if I use the method toString in the servlet, I obtain the right string (with "&oacute"), while if I use the method toString in the applet, I obtain the wrong string (with"&#243;")
I'm starting to think that perhaps the problem is in the methods I use to send and receive the xml message:
public void send (OutputStream out)
try
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
DOMSource source = new DOMSource(m_documento);
StreamResult result = new StreamResult (out);
transformer.transform (source, result);
catch (Exception e)
System.out.println("Error in method send: " + e.getMessage());
public Node receive (InputStream in)
try
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
StreamSource source = new StreamSource(in);
DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = dfactory.newDocumentBuilder();
mDocument = docBuilder.newDocument();
transformer.transform(source, new DOMResult (m_documento));
catch (Exception e)
System.out.println("Error in method receive: " + e.getMessage));
return null;
return mDocument;
What do you think? Thank you very much.

Similar Messages

  • 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()

  • DOM to String & String to DOM too Complicated

    Hi Java Comunity,
    I'm just wondering why one of the simplest tasks on the XML development such as creating (parsing) a DOM from a String and viceversa (Obtaining the XML as String from a DOM Document) is so Complicated.
    Obviously I'm a newbie in JAXP, but not in XML, the common sense dictaminates that these tasks should be as simple as something like:
    String xmlString = "<mytag>...</mytag>";
    org.w3c.dom.Document xmlDoc = new org.w3c.dom.Document(xmlString);
    and
    String anotherXmlString = xmlDoc.getXmlString();
    I already know how to perform these conversions, but I'm just wondering why you Java Developers enjoy making suffer all the programmers in the world with such complicated (and not intuitive) ways to perform simple tasks.
    Comunity, what do you think???

    This needs some cleanup, but it transforms an org.w3c.dom.Document object to a String.
    import java.io.*;
    import java.util.*;
    import javax.xml.transform.*;
    import javax.xml.transform.dom.*;
    import javax.xml.transform.stream.*;
    import org.w3c.dom.*;
    import org.xml.sax.*;
    public static String DocumentToString(Document doc)
    try
    ByteArrayOutputStream out;
    Transformer transformer;
    TransformerFactory tFactory;
    tFactory = TransformerFactory.newInstance();
    transformer = tFactory.newTransformer();
    out = new ByteArrayOutputStream();
    transformer.transform(new DOMSource(doc.getDocumentElement()), new StreamResult(out));
    if (out != null)
    return new String(out.toByteArray());
    else
    return null;
    catch (TransformerException te)
    te.printStackTrace();
    return null;

  • Namespace prefix in created DOM document string

    Hello world,
    I am creating a DOM document using the standard JAXP APIs. The document is not parsed from anywhere, just created using the DOM API factory methods. This document is a SOAP message with the SOAP envelope, header and body elements. Now I need to have this document transformed to an XML string.
    I can manage all this. However, I want to have the SOAP namespace set for the SOAP elements, and I want it set using a prefix (such as "SOAP-ENV" or "env" as in the example below). I have set the envelope, header and body element namespaces to the soap namespace. The rest of the elements inside header and body I have set to null namespace. I want them without any prefix (and what namespace will that be then, default?).
    The problem is, when I transform the document to a string, the namespace is set on the envelope without a prefix, and not on the header or body. I guess this is because the child elements will all inherit the namespace? I tried with xalan and saxon.
    Here is an example of output that would look like what I want:
    <env:Envelope xmlns:env="http://www.w3.org/2002/12/soap-envelope">
    <env:Header>
      <foo>hello</foo>
    </env:Header>
    <env:Body>
       <bar>is open</bar>
    </env:Body>
    </env:Envelope>Here is an example of output that looks like what I got:
    <Envelope xmlns="http://www.w3.org/2002/12/soap-envelope">
    <Header>
      <foo>hello</foo>
    </Header>
    <Body>
       <bar>is open</bar>
    </body>
    </Envelope>So so what am I doing wrong, how should I do it? If my rambling makes no sense, even an example of constructing output like the example of what I want would solve this.. :)
    Thanks,

    You could just create the an attribute like this:
    root.setAttribute("xmlns:env", "http://www.w3.org/2002/12/soap-envelope"); where root is the Envelope element.
    Hello world,
    I am creating a DOM document using the standard JAXP
    APIs. The document is not parsed from anywhere, just
    created using the DOM API factory methods. This
    document is a SOAP message with the SOAP envelope,
    header and body elements. Now I need to have this
    document transformed to an XML string.
    I can manage all this. However, I want to have the
    SOAP namespace set for the SOAP elements, and I want
    it set using a prefix (such as "SOAP-ENV" or "env" as
    in the example below). I have set the envelope,
    header and body element namespaces to the soap
    namespace. The rest of the elements inside header and
    body I have set to null namespace. I want them
    without any prefix (and what namespace will that be
    then, default?).
    The problem is, when I transform the document to a
    string, the namespace is set on the envelope without
    a prefix, and not on the header or body. I guess this
    is because the child elements will all inherit the
    namespace? I tried with xalan and saxon.
    Here is an example of output that would look like
    what I want:
    <env:Envelope
    xmlns:env="http://www.w3.org/2002/12/soap-envelope">
    <env:Header>
    <foo>hello</foo>
    </env:Header>
    <env:Body>
    <bar>is open</bar>
    </env:Body>
    </env:Envelope>Here is an example of output that looks like what I
    got:
    <Envelope
    xmlns="http://www.w3.org/2002/12/soap-envelope">
    <Header>
    <foo>hello</foo>
    </Header>
    <Body>
    <bar>is open</bar>
    </body>
    </Envelope>So so what am I doing wrong, how should I do it? If my
    rambling makes no sense, even an example of
    constructing output like the example of what I want
    would solve this.. :)
    Thanks,

  • Exception on creation of DOM from string xml

    Hi everybody,
    I am creating Dom from a string cml but getting following exception
    org.xml.sax.SAXParseException: name expected
    XML file is < name > < age > 23 < /age > < /name >
    JSP page is:-
    <%@ page import="java.util.*" %>
    <%@ page import="java.net.*" %>
    <%@ page import="javax.xml.parsers.*" %>
    <%@ page import="org.xml.sax.*" %>
    <%@ page import= "org.w3c.dom.*;" %>
    <HTML>
    <BODY>
    <%
    String str= request.getParameter("user");
    out.print(str);
    try{
    Document XMLDoc=DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new StringReader(str)));
    out.print(XMLDoc);
    catch( SAXParseException s){out.print("Parse excepttion occured   " + s + " Message is --> " + s.getMessage()   );}
    catch (SAXException sa){out.print("Sax Exception occured" + sa +"   " ) ;}
         catch (IOException fgh){out.print("IO Exception occured");}
         catch( ParserConfigurationException e) {out.print("Parser Configuration Exception occured"); }
    %>
    </BODY>
    </HTML>

    Hi Hamsa,
    Did you also create and configure an "Execution Destination"?
    You can test the Metadata destination configuration on Web Service Navigator.
    On the web service navigator (http://hostname:portnumber/wsnavigator) search in the metatda destination you have created for the service you imported in web dynpro as a model. If you can find it there test it on the ws navigator.
    Best regards,
    Yasar

  • Printing XML DOM to string

    When I create an xml document and print it to a string I find that I can only get 900 characters at a time from the output string (using substring) even though its length is reported as > 900
    Running on Oracle 8.1.7

    Sun's resources on XML (including JAXP):
    http://java.sun.com/xml/
    Parser with DOM and SAX support:
    http://xml.apache.org/xerces-j/
    http://www.alphaworks.ibm.com/tech/xml4j
    Of other interest:
    http://xml.apache.org/xalan/
    http://java.apache.org/ecs/index.html
    http://xml.apache.org/cocoon/index.html
    Cameron Purdy
    http://www.tangosol.com
    "Kevin Woo" <[email protected]> wrote in message
    news:[email protected]..
    Hi,
    Would anyone know where I could get a XML DOM to Java String parser,
    which does forward and backward parsing?
    Thanks a bunch,
    Kevin Woo

  • DOM to string in C++ Parser

    I see this has come up in various forms before, but what's the best way to convert from a DOM Document instance to a string (for saving to a file) using the C++ tools? I found Node::print(...) in the header file, but get a link error as if it's not really there. If you need a suggestion on what features to add, this would sure be one!

    You found the right method so I'm not sure why you get a link error. Can you supply some sample code and the linker output?

  • DOM - DOM transformation

    Hi all,
    I need to apply an XSL transformation to a DOM and I want to get a DOM as a result. This is no problem with Xalan or Saxon.
    I also want to use the Oracle XSL processor. Now this is where the problem starts: This processor tells me it only accepts SAX sources.
    My current workaround is this:
    1) transform DOM to String
    2) use String as a StreamSource, apply transformation, store result as String
    3) parse the resulting String as a DOM
    This
    * doesn't seem to be very elegant
    * is bound to have bad performance
    * actually seems to cause a problem because a namespace declaration is missing in the serialized transformation result and I cannot parse the result as a DOM (this happens very rarely, I have only encountered one transformation that had the problem, about 50 others seem to be fine...)
    What's the "proper" way of doing this?
    Thanks in advance for any insights!

    Hello dvorah,
    sorry for the late reply: There are no (email) notifications when a posting is edited and I therefore totally missed your correction...
    Well anyway: Unfortunately, those two links don't help at all, because they basically just describe what I am already doing (see above).
    Bottom line (of those postings) is: Can't be done. (except with "brute force" serialization and reparsing).
    Those postings are MORE THAN EIGHT YEARS OLD (spring of 2001) when Java 1.3 (!) was current and I'm really hoping that things have changed since then... I've done XML handling back then and it was a major pain (I quite like it now since Java 5)
    The way I see it, I could probably come up with a much much better solution (for one half of the problem) myself in a couple of hours (a SAX ContentHandler that builds a DOM from the events), I just don't feel like I should have to do that :-(((

  • Problem in producing some xml strings

    Dear all,
    I got a problem in producing some xml string. I use the DocumentBuilderFactory and DocumentBuilder to build a xml document. Instead of saving to a file, I need to make it into a string then return it to the caller. I have tried to use the Transformer but the string returned contains the <?xml version=..../> line which I don't want it. What can I do?

    What you want to do is associate a stylesheet with the transformer instance you are using to place the DOM into string. The stylesheet with the appropriate instructions are get rid of the <?xml version=..>. You want to produce a stylesheet which has:
    <xsl:output omit-xml-declaration="yes"/>
    <xsl:template match="/">
    <xsl:copy-of select="node()"/>
    </xsl:template>
    <xsl:output> controls the serialisation of the xml document to the output source which in this case is a string. The <xsl:template> is required. It will copy the entire xml document to the output source. Without it the default templates are used, and the xml markup will not be included in the output source.
    Hope this helps.

  • How can i getParameter then put inti DOM...

    <%@ page contentType="text/html; charset=iso-8859-1" language="java" import="java.sql.*" errorPage="" %>
    <%@ page import="javax.xml.parsers.*" %>
    <%@ page import="org.w3c.dom.*" %>
    <% String getCate = request.getParameter("category"); %>
    <html><head>
    <title>DOM Parser</title>
    </head>
    <body>
    <%  // Create the file object we will read from
      File f = new File("C:/Program Files/Tomcat 6.0/webapps/wsd/recipes/index.xml");
      // Create an instance of the DOM parser and parse the document
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      DocumentBuilder db = dbf.newDocumentBuilder();
      Document doc = db.parse(f);
      // Begin traversing the document
      traverseTree(doc, out);
    %>
    <%!
      //Get parameter from index to look up recipes follow category
      private void traverseTree(Node currnode, JspWriter out) throws Exception {
        // If the current node is null, do nothing
        if(currnode == null) {
          return;
         //out.println("<blockquote>");
        // Find the type of the current node
        int type = currnode.getNodeType();
        // Check the node type, and process it accordingly
        switch (type) {
        case Node.DOCUMENT_NODE:
          //out.println("<p>DOCUMENT</p>");
          traverseTree (((Document)currnode).getDocumentElement(), out);
          break;
        case Node.ELEMENT_NODE:
          //String elementName = currnode.getNodeName();
              //if (elementName.compareTo("title") == 0) {
          //     out.println("<p>ELEMENT: [" + elementName + "]</p>");
          //if (currnode.hasAttributes()) {
          //  NamedNodeMap attributes = currnode.getAttributes();
          //  for (int i=0; i < attributes.getLength(); i++) {
          //    Node currattr = attributes.item(i);
          //    traverseTree(currattr, out);
          NodeList childNodes = currnode.getChildNodes();     
          if(childNodes != null) {
            for (int i=0; i < childNodes.getLength() ; i++) {
              traverseTree (childNodes.item(i), out);
          break;
        case Node.ATTRIBUTE_NODE:
        //  String attributeName = currnode.getNodeName();
        //  String attributeValue = currnode.getNodeValue();
        // out.println("<p>ATTRIBUTE: name=[" + attributeName +
        //  "], value=[" + attributeValue + "]</p>");
          break;
    /*    case Node.TEXT_NODE: {
    *          Node parent = currnode.getParentNode();
    *          if (parent != null) {
    *               Node grandParent = parent.getParentNode();
    *               if (grandParent != null) {
    *                    if ((grandParent.getNodeName().equals("track")) && (parent.getNodeName().equals("title"))) {
    *                     String text = currnode.getNodeValue().trim();
    *                     if (text.length() > 0) {
    *                            out.println("<p>" + text + "</p>");
    *      break;
         case Node.TEXT_NODE: {
           Node parent = currnode.getParentNode();
           if (parent != null) {
                Node grandParent = parent.getParentNode();
              if ((grandParent.getNodeName().equals("recipe")) && (parent.getNodeName().equals("category"))) {
                String compare = currnode.getNodeValue();
                if (compare.equals(getCate)) {
                     String text = currnode.getNodeValue().trim();
                   if (text.length() > 0) {
                        out.println("<p>"+currnode.getPreviousSibling()+"<br />");
                        out.println(text+"<br />");
                        out.print(currnode.getNextSibling()+"</p>");
           break;
      //out.println("</blockquote>");
    %>
    <hr />
    </body></html>
    <%@page import="java.io.*, java.lang.*, java.net.*"%>I get a parameter from an html file (on line 4)
    <% String getCate = request.getParameter("category"); %>then use getCate as a String to compare with get current Node in DOM to print out
    String compare = currnode.getNodeValue();
                if (compare.equals(getCate))like this. But there is a problem...
    org.apache.jasper.JasperException: Unable to compile class for JSP:
    An error occurred at line: 110 in the jsp file: /process.jsp
    getCate cannot be resolved
    107:           if ((grandParent.getNodeName().equals("recipe")) && (parent.getNodeName().equals("category"))) {
    108:           
    109:           String compare = currnode.getNodeValue();
    110:           if (compare.equals(getCate)) {
    111:                String text = currnode.getNodeValue().trim();
    112:                if (text.length() > 0) {
    113:                     out.println("<p>"+currnode.getPreviousSibling()+"<br />");
    Stacktrace:
         org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErrorHandler.java:92)
         org.apache.jasper.compiler.ErrorDispatcher.javacError(ErrorDispatcher.java:330)
         org.apache.jasper.compiler.JDTCompiler.generateClass(JDTCompiler.java:423)
         org.apache.jasper.compiler.Compiler.compile(Compiler.java:316)
         org.apache.jasper.compiler.Compiler.compile(Compiler.java:294)
         org.apache.jasper.compiler.Compiler.compile(Compiler.java:281)
         org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:566)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:317)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:337)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:266)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
    I tried to to get it above the traverse tree but it didn't help either...
    What should i do.
    Thx

    1 more. when i put it above traverse tree, it appear is cannot resolve
    org.apache.jasper.JasperException: Unable to compile class for JSP:
    An error occurred at line: 24 in the jsp file: /process.jsp
    request cannot be resolved
    21:
    22: <%!
    23: //Get parameter from index to look up recipes follow category
    24: String getCate = request.getParameter("category");
    25:      
    26:      
    27: private void traverseTree(Node currnode, JspWriter out) throws Exception {
    Stacktrace:
         org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErrorHandler.java:92)
         org.apache.jasper.compiler.ErrorDispatcher.javacError(ErrorDispatcher.java:330)
         org.apache.jasper.compiler.JDTCompiler.generateClass(JDTCompiler.java:423)
         org.apache.jasper.compiler.Compiler.compile(Compiler.java:316)
         org.apache.jasper.compiler.Compiler.compile(Compiler.java:294)
         org.apache.jasper.compiler.Compiler.compile(Compiler.java:281)
         org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:566)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:317)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:337)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:266)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
    <%!
      //Get parameter from index to look up recipes follow category
      String getCate = request.getParameter("category");
      private void traverseTree(Node currnode, JspWriter out) throws Exception {
        // If the current node is null, do nothing
        if(currnode == null) {
          return;
    ...

  • Want to maintain order of attributes using DOM

    Have an XML file with this element
    <Name f="", b="", e="", d="", >
    i converted DOm to string using :
    TransformerFactory transformerFactory = TransformerFactory
    .newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    StringWriter sw = new StringWriter();
    transformer.transform(new DOMSource(doc), new StreamResult(sw));
    String stringDOM = sw.toString();
    It sorts the attributes in alphabetical order. now the element looks like
    <Name b="", d="", e="", f="",>
    I need to maintain the order. How can i do that? Is there any way to do so?

    You can't do that. XML specifically says the order of attributes doesn't matter, so if you're using a compliant parser to read the XML, you should not have to do that anyway.

  • Writing LARGE DOM objects

    Hi All,
    Any one has clue on how to write large DOM objects on to the HTTP response's Output stream.
    When i tried doing that I converted it to string and then transformed wrote to the stream.
    The problem is when I have a query that returns me around 8000 or more records the string is not fully formed. We get some malformed xml sent to the browser. So we are not able to view it using the stye sheets on the web browser.

    Hello Reflex,
    Do you mean you have any memory problem ?
    It looks like you are fetching data from database and sending it to browser like following:
    1) Convert ResultSet to DOM
    2) DOM to String
    3) String is directed to OutputStream/Writer of ServletResponse.
    You can see 1 and 2 are just waste of memory.
    Try knocking off any one or both of them. For Example,
    1) DOM object can directly written to OutputStream.
    2) You can use TransformerHandler to read database and directly write XML to OutputStream in terms of SAX events.

  • Issue with validation of signature

    Hello,
    I am facing a problem in producing a correct signature and I hope someone can help me understand the root of the problem. Most of us are familiar with the Java (Sun) examples of GenDetached, GenEnveloped, GenEnveloping, and Validate code samples. The code below is a small variation of the GenDetached:
    public class GenerateDetachedWithManifest {
      public static void main(String[] args) throws Exception {
        // First, create a DOM XMLSignatureFactory that will be used to
        // generate the XMLSignature and marshal it to DOM.
        String providerName = System.getProperty("jsr105Provider",
            "org.jcp.xml.dsig.internal.dom.XMLDSigRI");
        XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM",
            (Provider) Class.forName(providerName).newInstance());
        // Create a Reference to an external URI that will be digested
        // using the SHA1 digest algorithm
        Reference ref = fac.newReference("http://www.w3.org/TR/xml-stylesheet", fac
            .newDigestMethod(DigestMethod.SHA1, null));
        Reference xref = fac.newReference("#object", fac.newDigestMethod(
            DigestMethod.SHA1, null), null, "http://www.w3.org/2000/09/xmldsig#Object", null);
        Manifest manifest = fac.newManifest(Collections.singletonList(ref));
        List<XMLObject> objs = new ArrayList<XMLObject>();
        objs.add(fac.newXMLObject(Collections.singletonList(manifest), "object", null, null));
        // Create the SignedInfo
        SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod(
            CanonicalizationMethod.INCLUSIVE,
            (C14NMethodParameterSpec) null), fac.newSignatureMethod(
            SignatureMethod.DSA_SHA1, null), Collections.singletonList(xref));
        // Create a DSA KeyPair
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA");
        kpg.initialize(512);
        KeyPair kp = kpg.generateKeyPair();
        // Create a KeyValue containing the DSA PublicKey that was generated
        KeyInfoFactory kif = fac.getKeyInfoFactory();
        KeyValue kv = kif.newKeyValue(kp.getPublic());
        // Create a KeyInfo and add the KeyValue to it
        KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv));
        // Create the XMLSignature (but don't sign it yet)
        XMLSignature signature = fac.newXMLSignature(si, ki, objs, "SignatureIdValue", null);
        // Create the Document that will hold the resulting XMLSignature
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true); // must be set
        Document doc = dbf.newDocumentBuilder().newDocument();
        // Create a DOMSignContext and set the signing Key to the DSA
        // PrivateKey and specify where the XMLSignature should be inserted
        // in the target document (in this case, the document root)
        DOMSignContext signContext = new DOMSignContext(kp.getPrivate(), doc);
        // Marshal, generate (and sign) the detached XMLSignature. The DOM
        // Document will contain the XML Signature if this method returns
        // successfully.
        signature.sign(signContext);
        // output the resulting document
        OutputStream os;
        if (args.length > 0) {
          os = new FileOutputStream(args[0]);
        } else {
          os = System.out;
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer trans = tf.newTransformer();
        trans.transform(new DOMSource(doc), new StreamResult(os));
    }If you wonder why I am doing this the answer is that I am trying to sign a format based on OPC. Anyway, the problem I have is that the output of the above program fails to validate when running the Validate sample. I don't think the issue is with the Validate program because it correctly validates output of a .NET signing application whose behavior I am trying to replicate in Java.
    So the question is: why does the above code produce an incorrect signature?
    Thanks,
    Luis

    Can you post relevant sections of the OPC standard (or a link to it) that describes the requirement? Its possible that they have written the requirements differently from the examples. Its also possible that the DSIG library in the JDK only does things in a specifc way (I'll let Sean Mullan weigh in on this part of the discussion if he's monitoring this list/thread - he's the developer from Sun who wrote the library).
    Here's the wording from the W3C spec on the Object element:
    +"The Object's Id is commonly referenced from a Reference in SignedInfo, or Manifest. This element is typically used for enveloping signatures where the object being signed is to be included in the signature element. The digest is calculated over the entire Object element including start and end tags."+
    What you have is neither an Enveloping Signature nor Detached - but a combination of the two. So its possible that the JDK library doesn't work with Object references in this manner (although in theory is should). Based on this thread (XML dsig: Can I sign a SignatureProperty of the Signature? it appears that this theory holds up for child-elements of Object , but not for the Object element itself.
    Arshad Noor
    StrongAuth, Inc.

  • Counting rows in a report

    Hi,
    I have a report page based on a SQL query. I then have a button on that page and when the user clicks it, I want to be able to loop through each of the records in the report to do some processing. I was thinking of using a for loop but not sure how I determine the end number ie: for ii in 1 .. (Number of Rows in Report)? Any ideas?
    Thanks,
    Ben.

    Hi
    Check this out. It is part of the apex javascript library:
    * Check or uncheck (pCheck) all check boxs contained within a DOM node (pThis). If an array of checkboxs DOM nodes (pArray) is provided, use that array for affected check boxs.
    * @function
    * @param {DOM node | string ID} pThis
    * @param {true | false} pCheck
    * @param {DOM node Array} pArray
    function $f_CheckAll(pThis,pCheck,pArray){
         var l_Inputs;
         if(pArray){l_Inputs = pArray;}
         else{l_Inputs = $x_FormItems(pThis,'CHECKBOX');}
         for (var i=0,l=l_Inputs.length;i<l;i++){l_Inputs.checked = pCheck;}
         return;
    Edit - just spotted that are are tons of similar queries on this, just search for CheckAll in the forum.
    Let me know if you need further help.
    Cheers
    Ben
    Edited by: Munky on Apr 27, 2009 9:57 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • *** Serialization in SOAP ***

    Hi,
    I m building a web service with Jdeveloper 9.0.3 . I m trying to pass org.w3c.dom.Document in the function argument but got the following error:
    No Serializer found to serialize a &apos;org.w3c.dom.DOMImplementation&apos; using encoding style &apos;http://schemas.xmlsoap.org/soap/encoding/&apos;. [java.lang.IllegalArgumentException]
    Help,pls.
    Gary

    Ok, at the end of this e-mail see the stub that was generated from the Oracle9iAS side and a main method that calls your Web service - this should get you going. Before the code I will give you the steps I did:
    1. Make sure you delete the Web service you have deployed to OC4J before starting again (e.g. delete the directories <oc4j_home>\j2ee\home\application-deployments\gt-gt-WS, <oc4j_home>\j2ee\home\applications\gt-gt-WS, delete the file gt-gt-WS.ear from the <oc4j_home>\j2ee\home\applications\ directory and edit the file server.xml and remove the line: "<application name="gt-gt-WS" path="../applications/gt-gt-WS.ear" auto-start="true" />"
    2. Delete the stub/proxy you have generated from the JDeveloper WSDL
    3. Build your class as you did with a document parameter and return result
    4. Wrap it as a Web service using the JDev publishing wizard
    5. New step I missed previously: Before deploying to Oracle9iAS, right mouse click on the WebServices.deploy node and:
    * Select settings
    * Navigate to the classes node of the configuration tree
    * De-select the WSDL file
    * Exit from the configuration wizard by clicking on the OK button
    6. Deploy to Oracle9iAS by right mouse clicking on the Webservices.deploy node
    7. Go to the Web service endpoint (in your case: http://<your machine>:8888/gt-gt-context-root/XMLDocWS) in your browser. This can be found by editing the Web service node in JDeveloper and selecting "File Locations" and copying the URL in the field "Web service endpoint"
    8. From the endpoint page, copy the "Service Description" URL (i.e. the WSDL location) (e.g. CTRL-C). On mine, the URL is: http://<my machine>:8888/gt-gt-context-root/XMLDocWS?WSDL
    9. Go back to JDeveloper and in the project right mouse click on the project and select New->Web Service Stub/Skeleton.
    10. In the WSDL location, paste in the WSDL location you copied from the Web Service endpoint (http://<my machine>:8888/gt-gt-context-root/XMLDocWS?WSDL)
    11. Generate the new stub as normal.
    12. For a quick test copy in the main method I built below.
    From this point onwards your servlet you sent me should work.
    For others watching this thread, as this problem is generic, here is the service implementation:
    import org.w3c.dom.*;
    import oracle.xml.parser.v2.*;
    public class XMLDocWS
         public XMLDocWS()
         public Document query(org.w3c.dom.Document req)
    Document res = req;
              return res;
    Here is the stub that can be used to test it once you have published the above as a Web Service:
    import java.util.Vector;
    import java.net.URL;
    import java.util.Properties;
    import java.util.HashMap;
    import org.apache.soap.rpc.Call;
    import org.apache.soap.rpc.Parameter;
    import org.apache.soap.rpc.Response;
    import org.apache.soap.Fault;
    import org.apache.soap.SOAPException;
    import org.apache.soap.Constants;
    import org.apache.soap.encoding.SOAPMappingRegistry;
    import org.apache.soap.encoding.soapenc.BeanSerializer;
    import org.apache.soap.util.xml.QName;
    import oracle.soap.transport.http.OracleSOAPHTTPConnection;
    import oracle.soap.encoding.soapenc.EncUtils;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import oracle.xml.parser.v2.*;
    * Web service proxy: IXMLDocWS
    * generated by Oracle WSDL toolkit (Version: 1.0).
    public class IXMLDocWSProxy {
    public static void main(String[] args)
    try
    IXMLDocWSProxy stub = new IXMLDocWSProxy();
    XMLDocument doc = new XMLDocument();
    Element elAdd = doc.createElement("employee");
    Element elA = doc.createElement("name");;
    elA.appendChild(doc.createTextNode("Mike"));
    elAdd.appendChild(elA);
    doc.appendChild(elAdd);
    org.w3c.dom.Document in = (org.w3c.dom.Document)doc;
    org.w3c.dom.Document out = stub.query(in);
    XMLDocument out_print = (XMLDocument)out;
    ((XMLElement)out_print.getDocumentElement()).print(System.out);
    } catch (Exception ex)
    ex.printStackTrace();
    public IXMLDocWSProxy() {
    m_httpConnection = new OracleSOAPHTTPConnection();
    _setMaintainSession(true);
    Object untypedParams[] = {
    new String("query"), new String("output"), new QName("http://xmlns.oracle.com/2001/XMLSchema/DOM","org.w3c.dom.Document")
    String operationName;
    String paramName;
    QName returnType;
    SOAPMappingRegistry registry;
    org.apache.soap.util.xml.Deserializer deserializer;
    int x;
    for (x = 0; x < untypedParams.length; x += 3) {
    operationName = (String) untypedParams[x];
    paramName = (String) untypedParams[x+1];
    returnType = (QName) untypedParams[x+2];
    registry = (SOAPMappingRegistry) m_soapMappingRegistries.get(operationName);
    if (registry == null) {
    if (m_soapMappingRegistry != null) {
    registry = new SOAPMappingRegistry(m_soapMappingRegistry);
    } else {
    registry = new SOAPMappingRegistry();
    m_soapMappingRegistries.put(operationName,registry);
    try {
    deserializer = registry.queryDeserializer(returnType,Constants.NS_URI_SOAP_ENC);
    registry.mapTypes(Constants.NS_URI_SOAP_ENC, new QName("",paramName), null, null, deserializer);
    } catch(IllegalArgumentException e) {
    public org.w3c.dom.Document query(org.w3c.dom.Document param0) throws Exception {
    String soapActionURI = "urn:IXMLDocWS/query";
    String encodingStyleURI = "http://schemas.xmlsoap.org/soap/encoding/";
    Vector params = new Vector();
    params.add(new Parameter("param0", org.w3c.dom.Document.class, param0, null));
    Response response = makeSOAPCallRPC("query", params, encodingStyleURI, soapActionURI);
    Parameter returnValue = response.getReturnValue();
    return (org.w3c.dom.Document)returnValue.getValue();
    private Response makeSOAPCallRPC(String methodName, Vector params, String encodingStyleURI, String soapActionURI) throws Exception {
    Call call = new Call();
    call.setSOAPTransport(m_httpConnection);
    SOAPMappingRegistry registry;
    if ((registry = (SOAPMappingRegistry)m_soapMappingRegistries.get(methodName)) != null)
    call.setSOAPMappingRegistry(registry);
    else if (m_soapMappingRegistry != null)
    call.setSOAPMappingRegistry(m_soapMappingRegistry);
    call.setTargetObjectURI(m_serviceID);
    call.setMethodName(methodName);
    call.setEncodingStyleURI(encodingStyleURI);
    call.setParams(params);
    Response response = call.invoke(new URL(m_soapURL), soapActionURI);
    if (response.generatedFault()) {
    Fault fault = response.getFault();
    throw new SOAPException(fault.getFaultCode(), fault.getFaultString());
    return response;
    public String _getSoapURL() {
    return m_soapURL;
    public void _setSoapURL(String soapURL) {
    m_soapURL = soapURL;
    public String _getServiceID() {
    return m_serviceID;
    public void _setServiceID(String serviceID) {
    m_serviceID = serviceID;
    public SOAPMappingRegistry _getSOAPMappingRegistry() {
    return m_soapMappingRegistry;
    public void _setSOAPMappingRegistry(SOAPMappingRegistry soapMappingRegistry) {
    m_soapMappingRegistry = soapMappingRegistry;
    public boolean _getMaintainSession() {
    return m_httpConnection.getMaintainSession();
    public void _setMaintainSession(boolean maintainSession) {
    m_httpConnection.setMaintainSession(maintainSession);
    public Properties _getTransportProperties() {
    return m_httpConnection.getProperties();
    public void _setTransportProperties(Properties properties) {
    m_httpConnection.setProperties(properties);
    public String _getVersion() {
    return m_version;
    private String m_serviceID = "urn:IXMLDocWS";
    private String m_soapURL = "http://mlehmann-lap.us.oracle.com:8888/gt-gt-context-root/XMLDocWS";
    private OracleSOAPHTTPConnection m_httpConnection = null;
    private SOAPMappingRegistry m_soapMappingRegistry = null;
    private String m_version = "1.0";
    private HashMap m_soapMappingRegistries = new HashMap();
    Mike.

Maybe you are looking for