Appending xml documents

I have 4 xml documents and want to insert all three in one. what is the solution.
Thanks.
Crux

Create a new document to be the container
Remove the root element from each of the current other three documents.
Then appendChild() each one to the new container document.
Using XML Parser 9.0.0.0.0 you'll have to use the adoptNode() method to make sure that the new containing tree adopts the nodes from the other owning documents as its own.

Similar Messages

  • Can I append an XML Document into another?

    I have a large xml document which I open into coldfusion (mx
    7), and then a smaller group of files that are opened into thier
    own xml objects. After some customization of xml text values, I
    want to append the smaller xml documents into the larger document
    at specific positions within the document tree.
    I have the code that I thought would do this, using an
    arrayappend function, but what happens is that only the root
    element of the smaller (inserted) xml document is placed into the
    main document.
    Is this possible, or do I need to modify the code so that the
    entire tree of xml data that I am appending is created on the
    fly?

    Personally I do this with XSLT.
    <cfxml variable="doc1">
    <root>
    <member id="10">
    <name>Ian</name>
    <sex>male</sex>
    </member>
    </root>
    </cfxml>
    <cfxml variable="doc2">
    <root>
    <member id="1">
    <name>Joe</name>
    <sex>male</sex>
    </member>
    <member id="2">
    <name>John</name>
    <sex>male</sex>
    </member>
    <member id="3">
    <name>Sue</name>
    <sex>female</sex>
    </member>
    </root>
    </cfxml>
    <cffile action="write" file="#expandPath("/")#\doc2.xml"
    output="#ToString(doc2)#" nameconflict="overwrite">
    <!--- METHOD ONE using a depreciated and undocumented
    method --->
    <cfset newNode = doc1.root.member.cloneNode(true)>
    <cfset doc2.changeNodeOwner(newNode)>
    <cfset doc2.root.appendChild(newNode)>
    <cfdump var="#doc2#" label="Merged by hidden functions"
    expand="no">
    <!--- METHOD TWO using XSLT --->
    <!--- create an xsl docutment--->
    <cfoutput>
    <cfsavecontent variable="transformer">
    <xsl:stylesheet xmlns:xsl="
    http://www.w3.org/1999/XSL/Transform"
    version="1.0">
    <xsl:output method="xml"/>
    <!--load the merge file -->
    <xsl:variable name="emps"
    select="document('#expandPath("/")#\doc2.xml')"/>
    <!--- this line references and XML file to be combined
    with the main file,
    I wonder if there is a way to use an XML document in memory
    here? --->
    <!-- combine the files -->
    <xsl:template match="/">
    <root>
    <!-- select all the child nodes of the root tag in the
    main file -->
    <xsl:for-each select="root/child::*">
    <!-- copy the member tag -->
    <xsl:copy-of select="."/>
    </xsl:for-each>
    <!-- and all the child nodes of the root tag in the merge
    file -->
    <xsl:for-each select="$emps/root/child::*">
    <!-- copy the member tag -->
    <xsl:copy-of select="."/>
    </xsl:for-each>
    </root>
    </xsl:template>
    </xsl:stylesheet>
    </cfsavecontent>
    </cfoutput>
    <!--- create a combined xml document --->
    <cfset doc2 = XMLparse(XMLtransform(doc1,transformer))>
    <cfdump var="#doc2#" label="Merged by XSLT"
    expand="no">

  • How do you Append XML to an existing document?

    Hi there, I need to to append an existing XML document to a new XML document. How is this done?
    Is there an easy way of attaching one XML document to another?
    If not, do I need to parse the existing XML and add it to the new document, element by element?
    My existing XML is received as an input string and I need to include it in the new document.
    Thanks in advance
    Michael

    Hi there, I need to to append an existing XML document
    to a new XML document. How is this done?
    you can use JAXB to do this. unmarshall(), validate() and marshall() belonging to java intepretion of xml document.
    To eloborate further, say u have xml document as
    <book>
    <author>...</author>
    </book>
    JAXB helps u to get java intepretion of xml document by converting it into Book class and Author class.
    And, say u want to add new authors, u need to add Author objects to Book object and then pass Book object to marshall() method.
    The xml document will be appended with the author u added.
    Hope this helps.
    Jatin

  • How to append child to XML document using Java

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
    "http://www.springframework.org/dtd/spring-beans.dtd">
    <beans>
         <bean name="PinnacleReportsData"
              class="com.hsbc.webapp.report.view.GenericPinnacleReportsViewData"
              singleton="false">
              <property name="headers">
                   <value>Account|Cusip|Description|SecType|Sector|Holding|Price|MarketValue|SettleDate|Yield|SprdUST|AL|CFDur|OAS|ZVolOas|OADur|PrepayDur|VolDur|DV01|DVOAS01|KRDur10Y|PrepayModelCalled|CalcError|CalculationTime</value>
              </property>     
              <property name="noOfRows">
                   <value>20</value>
              </property>     
              <property name="rowdata">
                   <list>
                        <value>AA09b|CMO|8000|8000|62052MAD0|MFPLC_4A 2A 144A||8097|99-27+|5.18|0.25|200|0.00||15||||</value>
                        <value>AA09b|CMO|10000|10000|320277AD8|HASCO 2005 F II-A-2||9958|99-13|5.69|0.13|131|0.02||154|0.000|25|0.001|9864</value>
                        <value>AA09b|CMO|8000|2363|46071LAA8|IMT_03-3G A2||2378|100-01|5.18|0.14|33|0.00||2||||</value>
                        <value>AA09b|CMO|1270|312|40430HDW5|HASCO 2006-O II-A-1||309|99-00|8.98|0.16|5|0.01||3|0.000|1|0.001|296</value>
                        <value>AA09b|CMO|5000|5000|40430HFQ6|HASCO 2006-O M-3||4583|91-15+|8.99|1.16|534|-0.58|-2|-2644|0.016|712|0.080|367625</value>
                        <value>AA74b|ABS|8000|8000|62052MAD0|MFPLC_4A 2A 144A||8097|99-27+|5.18|0.25|200|0.00||15||||</value>
                        <value>AA74b|ABS|10000|10000|320277AD8|HASCO 2005 F II-A-2||9958|99-13|5.69|0.13|131|0.02||154|0.000|25|0.001|9864</value>
                        <value>AA74b|ABS|8000|2363|46071LAA8|IMT_03-3G A2||2378|100-01|5.18|0.14|33|0.00||2||||</value>
                        <value>AA74b|ABS|1270|312|40430HDW5|HASCO 2006-O II-A-1||309|99-00|8.98|0.16|5|0.01||3|0.000|1|0.001|296</value>
                        <value>AA74b|ABS|5000|5000|40430HFQ6|HASCO 2006-O M-3||4583|91-15+|8.99|1.16|534|-0.58|-2|-2644|0.016|712|0.080|367625</value>
                   </list>
              </property>
         </bean>
    </beans>               hi there i have a XML Document above,and i need to append values to the <list> using java.
    i have string values like
         <value>AA74b|ABS|5000|5000|40430HFQ6|HASCO 2006-O M-3||4583|91-15+|8.99|1.16|534|-0.58|-2|-2644|0.016|712|0.080|367625</value>to add, but failing to navigate to the <list>
    any help?

    1. Read the XML file into a DMO object, walk the DOM to find the list, insert your new entry as a child, write the DOM back to a file.
    2. If the XML is not in a file, but in a string, then you can do the same with string input and output.

  • Append XML elements with same name in an XML document

    Hi,
    I am using Oracle9i XMLDB utilities to modify an XML document stored in the database. I have a sample XML document like this in the database:
    <Person>
    <Address ID="1"> </Address>
    </Person>
    My task is to include a second <Address> element with a different attribute so that my XML document will become
    <Person>
    <Address ID="1"> </Address>
    <Address ID="2"> </Address>
    </Person>
    After creating the second element, I am using the function xmldom.appendChild() or xmldom.insertBefore() but they remove the first <Address> element and replace it with the second one. This is not what I want since I want both <Address> elements to be present.
    Could anyone please advise.
    Thanks.
    A. Dennis

    Please post your question [url http://forums.oracle.com/forums/forum.jsp?forum=154]here for quick response.
    thank you.
    Regards,
    Anupama
    [url http://otn.oracle.com/sample_code/]OTN Sample Code

  • Generating an XML Document from an internal table in ABAP

    Good day to all of you;
    With ABAP, in the R/3 system, I'm trying to figure out a way to accomplish the following:
    1) SELECT a set of Purchase Order data into an internal table.
    2) Generate an XML document, containing the above data, using a specific schema.
    I've been playing around with function module SAP_CONVERT_TO_XML_FORMAT which has the following interface:
    CALL FUNCTION 'SAP_CONVERT_TO_XML_FORMAT'
          EXPORTING
          I_FIELD_SEPERATOR    = ''
          I_LINE_HEADER        = ''
            I_FILENAME           = v_fname
          I_APPL_KEEP          = ''
          I_XML_DOC_NAME      = v_docname
          IMPORTING
            PE_BIN_FILESIZE      = v_byte
          TABLES
            I_TAB_SAP_DATA       = i_SapData
          CHANGING
            I_TAB_CONVERTED_DATA = i_XMLData
          EXCEPTIONS
            CONVERSION_FAILED    = 1
            OTHERS               = 2.
    I'm uncertain as to whether or not the Export parameter, I_XML_DOC_NAME refers to some schema or definition and therefore have been excluding it.  In doing so, the generated XML document seems to use the field name/type information from my itab for the tags.
    If this function module requires an XML Document Name, how do I create one and where do I store it in R/3?  If this is not the recommended solution, is anyone familiar with a way to load an XML schema, retrieve some data then have SAP generate an XML document using the schema?
    Many thanks for any help available.
    T

    Hai Phillips
    Try with the following Code
    This program exports an internal table to an XML file.
    Report ZPRUEBA_MML_13 *
    Export an internal table to XML document *
    NO BORRAR ESTE CODIGO *
    REPORT ZPRUEBA_MML_13.
    PANTALLA SELECCION *
        PARAMETERS: GK_RUTA TYPE RLGRAP-FILENAME.
    PANTALLA SELECCION *
    TYPE TURNOS *
    TYPES: BEGIN OF TURNOS,
        LU LIKE T552A-TPR01,
        MA LIKE T552A-TPR01,
        MI LIKE T552A-TPR01,
        JU LIKE T552A-TPR01,
        VI LIKE T552A-TPR01,
        SA LIKE T552A-TPR01,
        DO LIKE T552A-TPR01,
    END OF TURNOS.
    TYPE TURNOS *
    TYPE SOCIO *
    TYPES: BEGIN OF SOCIO,
        NUMERO LIKE PERNR-PERNR,
        REPOSICION LIKE PA0050-ZAUVE,
        NOMBRE LIKE PA0002-VORNA,
        TURNOS TYPE TURNOS,
    END OF SOCIO.
    TYPE SOCIO *
    ESTRUCTURA ACCESOS *
    DATA: BEGIN OF ACCESOS OCCURS 0,
        SOCIO TYPE SOCIO,
    END OF ACCESOS.
    ESTRUCTURA ACCESOS *
    START OF SELECTION *
    START-OF-SELECTION.
        PERFORM LLENA_ACCESOS.
        PERFORM DESCARGA_XML.
    END-OF-SELECTION.
    END OF SELECTION *
    FORM LLENA_ACCESOS *
    FORM LLENA_ACCESOS.
    REFRESH ACCESOS.
    CLEAR ACCESOS.
    MOVE: '45050' TO ACCESOS-SOCIO-NUMERO,
                  'MOISES MORENO' TO ACCESOS-SOCIO-NOMBRE,
                  '0' TO ACCESOS-SOCIO-REPOSICION,
                  'T1' TO ACCESOS-SOCIO-TURNOS-LU,
                  'T2' TO ACCESOS-SOCIO-TURNOS-MA,
                  'T3' TO ACCESOS-SOCIO-TURNOS-MI,
                  'T4' TO ACCESOS-SOCIO-TURNOS-JU,
                  'T5' TO ACCESOS-SOCIO-TURNOS-VI,
                  'T6' TO ACCESOS-SOCIO-TURNOS-SA,
                  'T7' TO ACCESOS-SOCIO-TURNOS-DO.
    APPEND ACCESOS.
    CLEAR ACCESOS.
    MOVE: '45051' TO ACCESOS-SOCIO-NUMERO,
                  'RUTH PEÑA' TO ACCESOS-SOCIO-NOMBRE,
                  '0' TO ACCESOS-SOCIO-REPOSICION,
                  'T1' TO ACCESOS-SOCIO-TURNOS-LU,
                  'T2' TO ACCESOS-SOCIO-TURNOS-MA,
                  'T3' TO ACCESOS-SOCIO-TURNOS-MI,
                  'T4' TO ACCESOS-SOCIO-TURNOS-JU,
                  'T5' TO ACCESOS-SOCIO-TURNOS-VI,
                  'T6' TO ACCESOS-SOCIO-TURNOS-SA,
                  'T7' TO ACCESOS-SOCIO-TURNOS-DO.
    APPEND ACCESOS.
    ENDFORM.
    FORM LLENA_ACCESOS *
    FORM DESCARGA_XML *
    FORM DESCARGA_XML.
    DATA: L_DOM TYPE REF TO IF_IXML_ELEMENT,
                  M_DOCUMENT TYPE REF TO IF_IXML_DOCUMENT,
                  G_IXML TYPE REF TO IF_IXML,
                  W_STRING TYPE XSTRING,
                  W_SIZE TYPE I,
                  W_RESULT TYPE I,
                  W_LINE TYPE STRING,
                  IT_XML TYPE DCXMLLINES,
                  S_XML LIKE LINE OF IT_XML,
                  W_RC LIKE SY-SUBRC.
    DATA: XML TYPE DCXMLLINES.
    DATA: RC TYPE SY-SUBRC,
    BEGIN OF XML_TAB OCCURS 0,
                  D LIKE LINE OF XML,
    END OF XML_TAB.
    CLASS CL_IXML DEFINITION LOAD.
    G_IXML = CL_IXML=>CREATE( ).
    CHECK NOT G_IXML IS INITIAL.
    M_DOCUMENT = G_IXML->CREATE_DOCUMENT( ).
    CHECK NOT M_DOCUMENT IS INITIAL.
    WRITE: / 'Converting DATA TO DOM 1:'.
    CALL FUNCTION 'SDIXML_DATA_TO_DOM'
    EXPORTING
                  NAME = 'ACCESOS'
                  DATAOBJECT = ACCESOS[]
    IMPORTING
                  DATA_AS_DOM = L_DOM
    CHANGING
                  DOCUMENT = M_DOCUMENT
    EXCEPTIONS
                  ILLEGAL_NAME = 1
                  OTHERS = 2.
    IF SY-SUBRC = 0.
                  WRITE 'Ok'.
    ELSE.
                  WRITE: 'Err =',
                  SY-SUBRC.
    ENDIF.
    CHECK NOT L_DOM IS INITIAL.
    W_RC = M_DOCUMENT->APPEND_CHILD( NEW_CHILD = L_DOM ).
    IF W_RC IS INITIAL.
                  WRITE 'Ok'.
    ELSE.
                  WRITE: 'Err =',
                  W_RC.
    ENDIF.
    CALL FUNCTION 'SDIXML_DOM_TO_XML'
    EXPORTING
                  DOCUMENT = M_DOCUMENT
    IMPORTING
                  XML_AS_STRING = W_STRING
                  SIZE = W_SIZE
    TABLES
                  XML_AS_TABLE = IT_XML
    EXCEPTIONS
                  NO_DOCUMENT = 1
                  OTHERS = 2.
    IF SY-SUBRC = 0.
                  WRITE 'Ok'.
    ELSE.
                  WRITE: 'Err =',
                  SY-SUBRC.
    ENDIF.
    LOOP AT IT_XML INTO XML_TAB-D.
                  APPEND XML_TAB.
    ENDLOOP.
    CALL FUNCTION 'WS_DOWNLOAD'
    EXPORTING
                  BIN_FILESIZE = W_SIZE
                  FILENAME = GK_RUTA
                  FILETYPE = 'BIN'
    TABLES
                  DATA_TAB = XML_TAB
    EXCEPTIONS
                  OTHERS = 10.
    IF SY-SUBRC <> 0.
                  MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
                  WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
    ENDIF.
    ENDFORM.
    FORM DESCARGA_XML *
    Thanks & regards
    Sreenivasulu P

  • Very urgent help needed- Error while passing XML document to Oracle stored

    Hi !
    I have been struggling a lot to call Oracle 9i stored procedure passing Stringbuilder object type from ASP.NET
    I am using Visual Studio 2008 Professional, OS: Windows XP and Oracle: 9.2.0.1.0
    Following is the procedure:
    CREATE or REPLACE PROCEDURE loadCompanyInfo (clobxml IN clob) IS
    -- Declare a CLOB variable
    ciXML clob;
    BEGIN
    -- Store the Purchase Order XML in the CLOB variable
    ciXML := clobxml;
    -- Insert the Purchase Order XML into an XMLType column
    INSERT INTO companyinfotbl (companyinfo) VALUES (XMLTYPE(ciXML));
    commit;
    --Handle the exceptions
    EXCEPTION
    WHEN OTHERS THEN
    raise_application_error(-20101, 'Exception occurred in loadCompanyInfo procedure :'||SQLERRM);
    END loadCompanyInfo ;
    And following is the ASP.net code:
    StringBuilder b = new StringBuilder();
    b.Append("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
    b.Append("<item>");
    b.Append("<price>500</price>");
    b.Append("<description>some item</description>");
    b.Append("<quantity>5</quantity>");
    b.Append("</item>");
    //Here you'll have the Xml as a string
    string myXmlString1 = b.ToString();
    //string result;
    using (OracleConnection objConn = new OracleConnection("Data Source=testdb; User ID=testuser; Password=pwd1"))
    OracleCommand objCmd = new OracleCommand();
    objCmd.Connection = objConn;
    objCmd.CommandText = "loadCompanyInfo";
    objCmd.CommandType = CommandType.StoredProcedure;
    //OracleParameter pmyXmlString1 = new OracleParameter("pmyXmlString1", new OracleString(myXmlString1));
    objCmd.Parameters.Add("myXmlString1", OracleType.clob);
    objCmd.Parameters.Add(myXmlString1).Direction = ParameterDirection.Input;
    //objCmd.Parameters.Add("result", OracleType.VarChar).Direction = ParameterDirection.Output;
    try
    objConn.Open();
    objCmd.ExecuteNonQuery();
    catch (Exception ex)
    Label1.Text = "Exception: {0}" + ex.ToString();
    objConn.Close();
    When I am trying to execute it, I am getting the following error:
    Exception: {0}System.Data.OracleClient.OracleException: ORA-06550: line 1, column 7: PLS-00306: wrong number or types of arguments in call to 'LOADCOMPANYINFO' ORA-06550: line 1, column 7: PL/SQL: Statement ignored at System.Data.OracleClient.OracleConnection.CheckError(OciErrorHandle errorHandle, Int32 rc) at System.Data.OracleClient.OracleCommand.Execute(OciStatementHandle statementHandle, CommandBehavior behavior, Boolean needRowid, OciRowidDescriptor& rowidDescriptor, ArrayList& resultParameterOrdinals) at System.Data.OracleClient.OracleCommand.ExecuteNonQueryInternal(Boolean needRowid, OciRowidDescriptor& rowidDescriptor) at System.Data.OracleClient.OracleCommand.ExecuteNonQuery() at Default.Button1Click(Object sender, EventArgs e)
    I understand from this that the .net type is not the correct one, but I am not sure how to correct it. I could not find any proper example in any documentation that I came across. Most of the examples give information on how to read but not how to insert XML into Oracle table by calling Stored Procedure.
    Can you please help me to solve this problem? I hope that you can help solve this.
    Also, can you please give me an example of passing XML document XMLdocument to Oracle Stored procedure.
    In both the cases, if you can provide the working code then it would be of great help.
    Thanks,

    Hi ,
    Additional to the Above error details my BPEL code looks like this:
    <process name="BPELProcess1"
    targetNamespace="http://xmlns.oracle.com/Application10/Project10/BPELProcess1"
    xmlns="http://schemas.xmlsoap.org/ws/2003/03/business-process/"
    xmlns:client="http://xmlns.oracle.com/Application10/Project10/BPELProcess1"
    xmlns:ora="http://schemas.oracle.com/xpath/extension"
    xmlns:bpelx="http://schemas.oracle.com/bpel/extension"
    xmlns:bpws="http://schemas.xmlsoap.org/ws/2003/03/business-process/">
    <partnerLinks>
    <partnerLink name="bpelprocess1_client" partnerLinkType="client:BPELProcess1" myRole="BPELProcess1Provider" partnerRole="BPELProcess1Requester"/>
    </partnerLinks>
    <variables>
    <variable name="inputVariable" messageType="client:BPELProcess1RequestMessage"/>
    <variable name="outputVariable" messageType="client:BPELProcess1ResponseMessage"/>
    </variables>
    <sequence name="main">
    <receive name="receiveInput" partnerLink="bpelprocess1_client" portType="client:BPELProcess1" operation="process" variable="inputVariable" createInstance="yes"/>
    <invoke name="callbackClient" partnerLink="bpelprocess1_client" portType="client:BPELProcess1Callback" operation="processResponse" inputVariable="outputVariable"/>
    </sequence>
    </process>
    Kindly help if anyone has faced this Issue before.
    Regards,
    Rakshitha

  • Parseing an XML Document as a String

    Hi all,
    i am trying to parse an XML document to a parser. I get the file as a request parameter, which is filled in to at String variable.
    But for some reason i get an SAXException, does anyone se the problem?
    Thank you for your help...
    Below is the code
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.util.*;
    import java.text.*;
    import java.net.*;
    import java.net.URL;
    import java.sql.*;
    import org.w3c.dom.Document;
    import org.w3c.dom.NamedNodeMap;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import org.xml.sax.SAXException;
    import org.xml.sax.SAXParseException;
    import javax.xml.parsers.*;
    import javax.xml.transform.stream.StreamSource;
    public class StartServlet extends HttpServlet
    private boolean debug = true;
    private final static String CONTENT = "content";
    private final static String COOKIES = "cookies";
    String resp = new String();
    private static String NODE_TYPES[] = new String[] {
         "ELEMENT",
         "ATTRIBUTE",
         "TEXT",
         "CDATA_SECTION",
         "ENTITY_REFERENCE",
         "ENTITY",
         "PROCESSING_INSTRUCTION",
         "COMMENT",
         "DOCUMENT",
         "DOCUMENT_TYPE",
         "DOCUMENT_FRAGMENT",
         "NOTATION" };
    public static void println(String s, int indent) {
         for(int i = 0 ; i < indent; i++) {
                   System.out.println(" ");
         System.out.println(s);
    public static void println(String s) {
         System.out.println(s);
    public static void print(Node node){
         printImpl(node, 0);
    public static void printImpl(Node node, int indent){
         if(node == null) {
              return;
         String nodeType = NODE_TYPES[node.getNodeType()];
         String nodeName = node.getNodeName();
         String nodeValue = node.getNodeValue();
         if(nodeValue != null) {
              nodeValue = nodeValue.trim();
         if(nodeType.equals("TEXT") && nodeValue.equals("")) {
              ; //Ignore emty node
         else {
              println(nodeType + " - " + nodeName + " - " + nodeValue, indent);
         NamedNodeMap attributes = node.getAttributes();
         if (attributes != null) {
              for(int i = 0; i < attributes.getLength(); i++) {
                   printImpl(attributes.item(i), indent + 1);
         NodeList children = node.getChildNodes();
         if(children != null) {
              for(int i = 0; i < children.getLength(); i++){
                   printImpl(children.item(i), indent + 1);
    public static DocumentBuilder newBuilder(boolean validation)
                        throws ParserConfigurationException {
         DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
         domFactory.setValidating(validation);
         domFactory.setNamespaceAware(true);
         DocumentBuilder domBuilder = domFactory.newDocumentBuilder();
         //domBuilder.setErrorHandler(new PrintErrorHandler());
         return domBuilder;
    public static Document newDocument()
                        throws ParserConfigurationException{
         DocumentBuilder domBuilder = newBuilder(false);
         Document document = domBuilder.newDocument();
         return document;
    public static Document parse( String xml, boolean validation)
                        throws ParserConfigurationException, IOException, SAXException {
              DocumentBuilder domBuilder = newBuilder(validation);
              Document document = domBuilder.parse(xml);
              return document;
    public void init() {
    public void service( javax.servlet.http.HttpServletRequest req, javax.servlet.http.HttpServletResponse res) {
              String[] cookies = null;
              try{
                   Hashtable document = getDocument("http://.../first.xml", cookies);
                   resp = (String) document.get(CONTENT);
                   debug(resp);
                   print(parse(resp, false));
              catch (SAXParseException e){
                   System.out.println("Saxfejl");
                   //System.exit(1);
              catch (Exception e){
                   e.printStackTrace();
                   System.exit(1);
    public void debug(String msg) {
         if(debug) {
              System.out.println(msg);
    public void performTask(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) {
         try
              // Insert user code from here.
         catch(Throwable theException)
              // uncomment the following line when unexpected exceptions
              // are occuring to aid in debugging the problem.
              //theException.printStackTrace();
    public void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, java.io.IOException {
         performTask(request, response);
    public void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, java.io.IOException {
         performTask(request, response);
    private Hashtable getDocument(String urlCode, String[] oldCookies) {
         Hashtable document = new Hashtable();
         HttpURLConnection http = null;
         try {
              URL httpURL = new URL(urlCode);
              // If HTTP Protocol, then open connection using the Request method indicated
              URLConnection conn = httpURL.openConnection();
              http = (HttpURLConnection) conn;
              //http.setRequestMethod("GET");
              http.setDoInput(true);
              http.setDoOutput(true);
              http.setUseCaches(false);
              http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
              if (oldCookies != null) {
                   for (int j = 0; j < oldCookies.length; j++) {
                        String cookie = oldCookies[j];
                        http.setRequestProperty("Cookie", cookie);
              http.connect();
              http.getContent();
              StringBuffer tsb = new StringBuffer("");
              if (http.getResponseCode() == 200) {
                   InputStream cis = http.getInputStream();
                   byte[] a = new byte[1024];
                   int n = cis.read(a);
                   while (n >= 0) {
                        tsb.append(new String(a, 0, n));
                        n = cis.read(a);
                   cis.close();
                   document.put(CONTENT, tsb.toString());
              String[] cookies = null;
              if (cookies == null) {
                   int headerFieldIndex = 0;
                   String headerFieldValue = http.getHeaderField(headerFieldIndex);
                   Vector cookieValues = new Vector();
                   while (headerFieldValue != null) {
                        String headerFieldName = http.getHeaderFieldKey(headerFieldIndex);
                        if ((headerFieldName != null) && headerFieldName.toLowerCase().equals("set-cookie")) {
                             int index = headerFieldValue.indexOf(";");
                             if (index > -1) {
                                  headerFieldValue = headerFieldValue.substring(0, index);
                             cookieValues.addElement(headerFieldValue);
                        headerFieldValue = http.getHeaderField(++headerFieldIndex);
                   cookies = new String[cookieValues.size()];
                   cookieValues.copyInto(cookies);
              document.put(COOKIES, cookies);
         catch (Exception e) {
              debug("url problem" + e);
         finally {
              if (http != null) {
                   http.disconnect();
         return document;
    }

    Hi,
    Use this code it will helpful to you.
    resultXMLDocument=(XmlDocument)documentDoc;
    StringWriter sw = new StringWriter();
    resultXMLDocument.write((Writer) sw);
    xmlString=sw.toString();
    thnaks,
    suneel

  • Can't get the DOM to output XML document tags in correct order.

    I'm trying to output an XML document from the DOM using the DOMWriter class: new DOMWriter(document, filename, outputEncoding, encodingTag, getDocTypeString());
    It refuses to output the tags in the correct order so my document always fails validation when it is read back in. I've tried explicitly placing the elements in the correct order into the DOM and it still outputs them the way it wants to. Is there some method I'm missing to set the xsd or dtd to validate the output on. It actually appears as though it has a definite idea as to what order the tags should be output, because no matter what order I append the nodes into the document, it always outputs them in the same incorrect order. I've got the validation working when it reads the document in. Does anyone know what I have to do to get it to output the tags in the correct order?

    Does anyone know what I
    have to do to get it to output the tags in the correct
    order?You have to build the DOM in the correct way. Based on the code you posted it's impossible to tell what you are doing wrong. How about posting some code?

  • XML document must have a top level element. Error processing resource

    Hi,
    I am trying to send a XML file to a web browser from a servlet. I read the contents of the XML file into a string and I am sending it to the brower. Before I do this I set the 'Content-type' header of the httpResponse to "application/xml" . Embedded in the XML file is an xml-stylesheet elemetn indicating which *.xsl stylesheet to use to parse the XML content.
    I get the following error:
    The XML page cannot be displayed
    Cannot view XML input using XSL style sheet. Please correct the error and then click the Refresh button, or try again later.
    XML document must have a top level element. Error processing resource 'http://127.0.0.1:8080/testReplyingXML/xml-to-html.xs...
    Now, if I take the stylesheet element out of the XML string I sent, then the browser stores the content into and *.xml file. I manually run the "xml-to-xsl " stylesheet mentioned in the error output above, and there is no problem, the xml content gets successfully transformed in a viewable HTML .
    It is only when I embed the "stylesheet" element into the XML content that I get this error.
    So the browser is receiveing valid XML.
    I am not sure if the above error is complaining about the XML content I send or the stylesshet .
    Does anyone have an idea of what am I doing wrong?
    For your information here are my servlet code and the XML file:
    servlet:-
    package webapps.testReplyingXML;
    import java.io.BufferedReader;
    import java.io.IOException;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.FileReader;
    import java.util.Enumeration;
    import java.util.StringTokenizer;
    import java.io.PrintWriter;
    public class ReplyXML extends HttpServlet {
              static int transactionCount = 0;
              public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException ,IOException {
                   String Q_PARAM = "query";
                   String requestString = req.getQueryString();
                   for ( Enumeration en = req.getParameterNames() ; en.hasMoreElements() ; )
         String k = (String)en.nextElement() ;
         String[] x = req.getParameterValues(k) ;
         String s = null;
         String DATA_PARAM= "";
         for(int i = 0 ; i < x.length ; i++ )
         s = x[i] ;
         //System.out.println("s = " + s);
         if (k.equals("query")){
              try {
                             //res.setHeader("Content-Type", "application/xml");
                             //res.setHeader("Transfer-Encoding", "chunked");
                             //res.setHeader("Cache-Control", "no-cache");
                             //res.setHeader("Server", "Jetty/5.1.10");
                             //res.setHeader("Pragma", "no-cache");
                             //res.setHeader("X-Joseki-Server", "Joseki-3.0-dev");
                             res.setStatus(res.SC_OK);
                             StringBuffer fileData = new StringBuffer(1000);
                        BufferedReader reader = new BufferedReader(new FileReader("sparql_results.xml"));
                        char[] buf = new char[1024];
                        int numRead=0;
                        while((numRead=reader.read(buf)) != -1){
                        String readData = String.valueOf(buf, 0, numRead);
                        fileData.append(readData);
                        buf = new char[1024];
                        reader.close();
                        String xmlMsg= fileData.toString();
                        System.out.println("XMLMSG= " + xmlMsg);
                             PrintWriter outresp = res.getWriter();
                             outresp.println(xmlMsg);
                             outresp.close();
              }catch (Exception e) {
                   e.printStackTrace();
              public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
                   doGet(req, res);
    XML FILE:
    <?xml version="1.0"?>
    <?xml-stylesheet type="text/xsl" href="xml-to-html.xsl"?>
    <sparql
    xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
    xmlns:xs="http://www.w3.org/2001/XMLSchema#"
    xmlns="http://www.w3.org/2005/sparql-results#" >
    <head>
    <variable name="book"/>
    <variable name="title"/>
    </head>
    <results ordered="false" distinct="false">
    <result>
    <binding name="book">
    <uri>http://example.org/book/book6</uri>
    </binding>
    <binding name="title">
    <literal>Harry Potter and the Half-Blood Prince</literal>
    </binding>
    </result>
    <result>
    <binding name="book">
    <uri>http://example.org/book/book5</uri>
    </binding>
    <binding name="title">
    <literal>Harry Potter and the Order of the Phoenix</literal>
    </binding>
    </result>
    <result>
    <binding name="book">
    <uri>http://example.org/book/book4</uri>
    </binding>
    <binding name="title">
    <literal>Harry Potter and the Goblet of Fire</literal>
    </binding>
    </result>
    <result>
    <binding name="book">
    <uri>http://example.org/book/book3</uri>
    </binding>
    <binding name="title">
    <literal>Harry Potter and the Prisoner Of Azkaban</literal>
    </binding>
    </result>
    <result>
    <binding name="book">
    <uri>http://example.org/book/book2</uri>
    </binding>
    <binding name="title">
    <literal>Harry Potter and the Chamber of Secrets</literal>
    </binding>
    </result>
    <result>
    <binding name="book">
    <uri>http://example.org/book/book1</uri>
    </binding>
    <binding name="title">
    <literal>Harry Potter and the Philosopher's Stone</literal>
    </binding>
    </result>
    </results>
    </sparql>

    Error processing resource http://127.0.0.1:8080/testReplyingXML/xml-to-html.xs...
    Well, if one more character had been deleted from that message then you would have a problem. But as it is, the error message says there's an error processing a resouce whose name ends with "xml-to-html.xs" followed by something. That would be the stylesheet if I'm not mistaken. Most likely the browser can't find it at the URL mentioned in the error message.

  • Inserting an element into an XML document

    I am simply looking insert a new element into an existing XML Document using JDOM. Here is my code so far:
    public class UserDocumentWriter {
         private SAXBuilder builder;
         private Document document;
         private File file = new File("/path/to/file/users.xml");
         private Element rootElement;
         public UserDocumentWriter() {
              builder = new SAXBuilder();
              try {
                   document = builder.build(file);
                   rootElement = document.getRootElement();
              } catch (IOException ioe) {
                   System.err.println("ERROR: Could not build the XML file.");
              } catch (JDOMException jde) {
                   System.err.println("ERROR: " + file.toString() + " is not well-formed.");
         public void addContact(String address, String contact) {
              List contactList = null;
              Element contactListElement;
              Element newContactElement = new Element("contact");
              newContactElement.setText(contact);
              List rootsChildren = rootElement.getChildren();
              Iterator iterator = rootsChildren.iterator();
              while (iterator.hasNext()) {
                   Element e = (Element) iterator.next();
                   if (e.getAttributeValue("address").equals(address)) {
                        contactListElement = e.getChild("contactlist");
                        contactListElement.addContent(newContactElement);
                        writeDocument(document);
         public void writeDocument(Document doc) {
              try {
                   XMLOutputter output = new XMLOutputter();
                   OutputStream out = new FileOutputStream(file);
                   output.output(doc, out);
              } catch (FileNotFoundException ntfe) {
                   System.err.println("ERROR: Output file not found.");
              } catch (IOException ioe) {
                   System.err.println("Could not output document changes.");
         }However, the problem is, the newly added element will always be appended to the end of the last line, resulting in the following:
    <contactlist>
                <contact>[email protected]</contact><contact>[email protected]</contact></contactlist>Is there anyway in which I can have the newly added element create it's own line for the purpose of tidy XML? Alternatively is there a better methodology to do the above entirely?

    Your question is not very clear.
    Do you want to know How to insert an element into an XML document?
    Answer: I can see you already know how to do it. You have added the element using addContent()
    or do you want to know How to display the XML in a tidy format?
    Answer: to view the XML in a properly formatted style you can you the Format class. A very basic way of viewing the XML would be:
       * Prints the Document to the specified file.
       * @param doc
       * @param filename
       * @param formatting
      public static void printDocToFile(Document doc, String strFileName,
          boolean formatting)
        XMLOutputter xmlOut = null;
        if (!formatting)
          xmlOut = new XMLOutputter();
        } else
          Format prettyFormat = Format.getPrettyFormat();
          prettyFormat.setOmitEncoding(false);
          prettyFormat.setOmitDeclaration(false);
          xmlOut = new XMLOutputter(prettyFormat);
        try
          if (doc != null)
            FileWriter writer = new java.io.FileWriter(strFileName, true);
            xmlOut.output(doc, writer);
            writer.flush();
            writer.close();
          } else
            System.out.println("Document is null.");
        catch (Exception ex)
          System.out.println(ex);
      }

  • Remove first line in the XML Document

    Hi Friends,
    In my File to File scenario when ever new mesg is appending to file at receiver side,it should remove <?xml version="1.0" encoding="ISO-8859-1"?>  tag from the XML Document.This means <?xml version="1.0" encoding="ISO-8859-1"?> tag should appear once in a document.Plz suggest me to do this.
    Thanks
    pullarao.

    Hi there,
    you can either use XSLT (with output type="text") or Java, using the code:
    try {
      DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
      Document doc = docBuilder.parse(in);
      TransformerFactory tf = TransformerFactory.newInstance();
      Transformer trans = tf.newTransformer();
      trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
      DOMSource source = new DOMSource(doc);
      OutputStream out = new ByteArrayOutputStream();
      trans.transform(source, new StreamResult(out));
    } catch (...
    But as Bhavesh said, append mode is not recommended for XML files.
    Best approach is collect pattern on BPM.
    Regards,
    Henrique.

  • XML document structures must start and end within the same entity

    Hi there,
    I'm working with a client/server application and using SaxParser for reading in xml. I get the SaxParserException: XML document structures must start and end within the same entity. I understand what that means, but it isn't applicable! The xml data being used is well-formed. I checked the well-formedness with Stylus Studio to make sure. Here's the data:
    <?xml version='1.0' encoding='UTF-8'?>
    <vcmessage>
         <vcsource>3</vcsource>
         <processevent>16</processevent>
         <shape>
              <llindex>0</llindex>
              <shapetype>9</shapetype>
              <shapeproperties>
                   <shapelocation>
                        <xcoord>54</xcoord>
                        <ycoord>184</ycoord>
                   </shapelocation>
                   <bounds>
                        <width>24</width>
                        <height>24</height>
                   </bounds>
                   <fgcolor>
                        <fgred>0</fgred>
                        <fggreen>0</fggreen>
                        <fgblue>0</fgblue>
                   </fgcolor>
                   <bgcolor>
                        <bgred>255</bgred>
                        <bggreen>255</bggreen>
                        <bgblue>255</bgblue>
                   </bgcolor>
                   <thickness>1</thickness>
                   <isfilled>false</isfilled>
              </shapeproperties>
         </shape>
    </vcmessage>The parser generally stops around the </bgcolor> tag.
    I'm using Eclypse as my IDE. I'm wondering if there's something wrong with it? Or maybe there's something wrong with the class I'm using for reading in the XML? Followng is the class.
    Please advise,
    Alan
    package vcclient;
    import java.io.*;
    import org.xml.sax.*;
    import org.xml.sax.helpers.*;
    import javax.xml.parsers.*;
    public class XMLDocumentReader extends DefaultHandler
      private VCClient client = null;
      private Writer out;
      private String lineEnd =  System.getProperty("line.separator");
      private boolean haveSourceType = false;
      private boolean haveUserName = false;
      private boolean haveMessage = false;
      private boolean haveProcessEvent = false;
      private boolean haveLinkedListIndex = false;
      private boolean haveOpeningShapePropertiesTag = false;
      private boolean haveShapeType = false;
      private boolean haveOpeningShapeLocationTag = false;
      private boolean haveShapeLocation = false;
      private boolean haveOpeningXCoordTag = false;
      private boolean haveOpeningYCoordTag = false;
      private boolean haveOpeningBoundsTag = false;
      private boolean haveBoundsWidth = false;
      private boolean haveBoundsHeight = false;
      private boolean haveOpeningFGColorTag = false;
      private boolean haveOpeningBGColorTag = false;
      private boolean haveOpeningThicknessTag = false;
      private boolean haveOpeningIsFilledTag = false;
      private boolean haveOpeningImageDataTag = false;
      private boolean haveOpeningTextDataTag = false;
      private boolean haveFGRed = false;
      private boolean haveFGGreen = false;
      private boolean haveFGBlue = false;
      private boolean haveBGRed = false;
      private boolean haveBGGreen = false;
      private boolean haveBGBlue = false;
      private boolean haveThickness = false;
      private boolean haveIsFilled = false;
      private boolean haveImageData = false;
      private boolean haveTextData = false;
      private VCMessage vcmessage = null;
      public XMLDocumentReader(VCClient value)
           client = value;
           vcmessage = new VCMessage();
      public VCMessage getVCMessage()
           return vcmessage;
      public boolean haveSourceType()
         return haveSourceType; 
      public boolean ParseXML(InputStream stream)
         boolean success = false;
         // Use the default (non-validating) parser
        SAXParserFactory factory = SAXParserFactory.newInstance();
        try
             // Set up output stream
            out = new OutputStreamWriter(System.out, "UTF-8");
            // Parse the input
            SAXParser saxParser = factory.newSAXParser();
            saxParser.parse( stream, this );
            success = true;
        catch (SAXParseException spe)
            // Error generated by the parser
            System.out.println("\n** Parsing error"
               + ", line " + spe.getLineNumber()
               + ", uri " + spe.getSystemId());
            System.out.println("   " + spe.getMessage() );
            // Unpack the delivered exception to get the exception it contains
            Exception  x = spe;
            if (spe.getException() != null)
                x = spe.getException();
            x.printStackTrace();
            return success;
        catch (SAXException sxe)
             // Error generated by this application
             // (or a parser-initialization error)
             Exception  x = sxe;
             if (sxe.getException() != null)
                 x = sxe.getException();
             x.printStackTrace();
             return success;
        catch (ParserConfigurationException pce)
            // Parser with specified options can't be built
            pce.printStackTrace();
            return success;
        catch (Throwable t)
             t.printStackTrace();
             return success;
        return success;
      public void startDocument()throws SAXException
          emit("<?xml version='1.0' encoding='UTF-8'?>");
          nl();
      public void endDocument()throws SAXException
          try {
              nl();
              out.flush();
          } catch (IOException e) {
              throw new SAXException("I/O error", e);
      public void startElement(String namespaceURI,
                               String lName, // local name
                               String qName, // qualified name
                               Attributes attrs)throws SAXException
          String eName = lName; // element name
          if (eName.equals(""))
             eName = qName; // namespaceAware = false
          emit("<"+eName);
          if (attrs != null) {
              for (int i = 0; i < attrs.getLength(); i++) {
                  String aName = attrs.getLocalName(i); // Attr name
                  if (aName.equals("")) aName = attrs.getQName(i);
                  emit(" ");
                  emit(aName + "=\"" + attrs.getValue(i) + "\"");
          emit(">");
          if(makeStartTag(eName).equals(Constants.OPENING_SHAPEPROPERTIES))
                haveOpeningShapePropertiesTag = true;
          else if(makeStartTag(eName).equals(Constants.OPENING_SHAPELOCATION))
              haveOpeningShapeLocationTag = true;
          else if(makeStartTag(eName).equals(Constants.OPENING_BOUNDS))
                haveOpeningBoundsTag = true;
          else if(makeStartTag(eName).equals(Constants.OPENING_FGCOLOR))
                 haveOpeningFGColorTag = true;
          else if(makeStartTag(eName).equals(Constants.OPENING_BGCOLOR))
              haveOpeningBGColorTag = true;
          else if(makeStartTag(eName).equals(Constants.OPENING_BGGREEN))
               System.out.println("See BGGreen");
          else if(makeStartTag(eName).equals(Constants.OPENING_BGBLUE))
               System.out.println("See BGBlue");
          else if(makeStartTag(eName).equals(Constants.OPENING_THICKNESS))
              haveOpeningThicknessTag = true;
          else if(makeStartTag(eName).equals(Constants.OPENING_ISFILLED))
              haveOpeningIsFilledTag = true;
          else if(makeStartTag(eName).equals(Constants.OPENING_IMAGEDATA))
              haveOpeningImageDataTag = true;
          else if(makeStartTag(eName).equals(Constants.OPENING_TEXTDATA))
              haveOpeningTextDataTag = true;
      public void endElement(String namespaceURI,
                             String sName, // simple name
                             String qName  // qualified name
                            )throws SAXException
           if(sName.equals("") && !qName.equals(""))
              sName = qName;
              emit("</"+sName+">");
           else
              emit("</"+sName+">");
           if(makeEndTag(sName).equals(Constants.CLOSING_SOURCE_TYPE))
              haveSourceType = true;
           else if(makeEndTag(sName).equals(Constants.CLOSING_USER))
              haveUserName = true;
           else if(makeEndTag(sName).equals(Constants.CLOSING_MESSAGE))
              haveMessage = true;
           else if(makeEndTag(sName).equals(Constants.CLOSING_PROCESSEVENT))
               haveProcessEvent = true;
           else if(makeEndTag(sName).equals(Constants.CLOSING_LINKEDLISTINDEX))
               haveLinkedListIndex = true;
           else if(makeEndTag(sName).equals(Constants.CLOSING_SHAPETYPE))
               haveShapeType = true;
           else if(makeEndTag(sName).equals(Constants.CLOSING_SHAPELOCATION))
                haveOpeningShapeLocationTag = false;
           else if(makeEndTag(sName).equals(Constants.CLOSING_WIDTH))
               haveBoundsWidth = true;
           else if(makeEndTag(sName).equals(Constants.CLOSING_HEIGHT))
               haveBoundsHeight = true;
           else if(makeEndTag(sName).equals(Constants.CLOSING_BOUNDS))
                haveOpeningBoundsTag = false;
           else if(makeEndTag(sName).equals(Constants.CLOSING_FGRED))
               haveFGRed = true;
           else if(makeEndTag(sName).equals(Constants.CLOSING_FGGREEN))
               haveFGGreen = true;
           else if(makeEndTag(sName).equals(Constants.CLOSING_FGBLUE))
               haveFGBlue = true;
           else if(makeEndTag(sName).equals(Constants.CLOSING_FGCOLOR))
                haveOpeningFGColorTag = false;
           else if(makeEndTag(sName).equals(Constants.CLOSING_BGRED))
               haveBGRed = true;
           else if(makeEndTag(sName).equals(Constants.CLOSING_BGGREEN))
             haveBGGreen = true;
           else if(makeEndTag(sName).equals(Constants.CLOSING_BGBLUE))
               System.out.println("See closing BGBlue");
               haveBGBlue = true;
           else if(makeEndTag(sName).equals(Constants.CLOSING_BGCOLOR))
                haveOpeningBGColorTag = false;
           else if(makeEndTag(sName).equals(Constants.CLOSING_THICKNESS))
               System.out.println("XMLDocumentReader: Step2");
                haveOpeningThicknessTag = false;
           else if(makeEndTag(sName).equals(Constants.CLOSING_ISFILLED))
               haveOpeningIsFilledTag = false;
           else if(makeEndTag(sName).equals(Constants.CLOSING_IMAGEDATA))
               haveOpeningImageDataTag = false;
           else if(makeEndTag(sName).equals(Constants.CLOSING_TEXTDATA))
               haveOpeningTextDataTag = false;
      private String makeStartTag(String tag_name)
           String start = "<";
           String end = ">";
           return start.concat(tag_name).concat(end);
      private String makeEndTag(String tag_name)
           String start = "</";
           String end = ">";
           return start.concat(tag_name).concat(end);
      public void characters(char buf[], int offset, int len)throws SAXException
           String s = new String(buf, offset, len);
          if(haveSourceType == false)
               if(vcmessage.getSourceType() == null)
                  try
                    if(s.equals(""))return;
                   int sourcetype = Integer.parseInt(s);
                   vcmessage.setSourceType(sourcetype);                            
                  catch(NumberFormatException nfe){}
          else if(vcmessage.getSourceType() == SourceType.CHAT_SOURCE)
            if(vcmessage.getSourceType() == SourceType.CHAT_SOURCE && haveUserName == false)
                 vcmessage.setUserName(s);          
            else if(vcmessage.getSourceType() == SourceType.CHAT_SOURCE && haveMessage == false)
               //When the parser encounters interpreted characters like: & or <,
               //then this method gets invoked more than once for the whole message.
               //Therefore, we need to concatonate each portion of the message.  The
               //following method call automatically concatonates.
               vcmessage.concatMessage(s);                    
          else if(vcmessage.getSourceType() == SourceType.WHITEBOARD_SOURCE)
               if(haveProcessEvent == false)
                 try
                   vcmessage.setProcessEvent(Integer.parseInt(s));
                 catch(NumberFormatException nfe){}
               else if(haveLinkedListIndex == false)
                    try
                       vcmessage.setLinkedListIndex(Integer.parseInt(s));
                     catch(NumberFormatException nfe){}
               else if(haveShapeType == false)
                    try
                       vcmessage.setShapeType(Integer.parseInt(s));
                     catch(NumberFormatException nfe){}
               if(haveOpeningShapePropertiesTag)
                    if(haveOpeningShapeLocationTag)
                         if(haveOpeningXCoordTag)
                              try
                                vcmessage.setXCoordinate(Integer.parseInt(s));
                              catch(NumberFormatException nfe){}
                         else if(haveOpeningYCoordTag)
                              try
                                vcmessage.setYCoordinate(Integer.parseInt(s));
                                //reset all flags for ShapeLocation, X and Y coordinates
                                haveOpeningXCoordTag = false;
                                haveOpeningYCoordTag = false;
                                //haveOpeningShapeLocationTag = false;
                              catch(NumberFormatException nfe){}
                    else if(haveOpeningBoundsTag)
                         if(haveBoundsWidth == false)
                              try
                                vcmessage.setBoundsWidth(Integer.parseInt(s));
                              catch(NumberFormatException nfe){}
                         else if(haveBoundsHeight == false)
                              try
                                vcmessage.setBoundsHeight(Integer.parseInt(s));
                                //reset flag
                                //haveOpeningBoundsTag = false;
                              catch(NumberFormatException nfe){}
                    else if(haveOpeningFGColorTag)
                         if(haveFGRed == false)
                              try
                                vcmessage.setFGRed(Integer.parseInt(s));                           
                              catch(NumberFormatException nfe){}
                         else if(haveFGGreen == false)
                              try
                                vcmessage.setFGGreen(Integer.parseInt(s));                           
                              catch(NumberFormatException nfe){}
                         else if(haveFGBlue == false)
                              try
                                vcmessage.setFGBlue(Integer.parseInt(s));
                                //reset flag
                                //haveOpeningFGColorTag = false;
                              catch(NumberFormatException nfe){}
                    else if(haveOpeningBGColorTag)
                         if(haveBGRed == false)
                              try
                                vcmessage.setBGRed(Integer.parseInt(s));                           
                              catch(NumberFormatException nfe){}
                         else if(haveBGGreen == false)
                              try
                                vcmessage.setBGGreen(Integer.parseInt(s));                           
                              catch(NumberFormatException nfe){}
                         else if(haveBGBlue == false)
                         {   System.out.println("getting BGBlue data");
                              try
                                vcmessage.setBGBlue(Integer.parseInt(s));
                                //reset flag
                                //haveOpeningBGColorTag = false;
                              catch(NumberFormatException nfe){}
                    else if(haveOpeningThicknessTag)
                         try
                            vcmessage.setThickness(Integer.parseInt(s));                       
                          catch(NumberFormatException nfe){}
                    else if(haveOpeningIsFilledTag)
                         vcmessage.setIsFilled(s);
                    else if(haveOpeningImageDataTag && vcmessage.getProcessEvent() == org.jcanvas.comm.ProcessEvent.MODIFY)
                         vcmessage.setBase64ImageData(s);                    
                    else if(haveOpeningTextDataTag && vcmessage.getProcessEvent() == org.jcanvas.comm.ProcessEvent.MODIFY)
                         vcmessage.setTextData(s);
                    //reset
                    haveOpeningShapePropertiesTag = false;
          emit(s);
      //===========================================================
      // Utility Methods ...
      //===========================================================
      // Wrap I/O exceptions in SAX exceptions, to
      // suit handler signature requirements
      private void emit(String s)throws SAXException
          try {
              out.write(s);
              out.flush();
          } catch (IOException e) {
              throw new SAXException("I/O error", e);
      // Start a new line
      private void nl()throws SAXException
          try {
              out.write(lineEnd);
          } catch (IOException e) {
              throw new SAXException("I/O error", e);
      //treat validation errors as fatal
      public void error(SAXParseException e)
      throws SAXParseException
        throw e;
      // dump warnings too
      public void warning(SAXParseException err)
      throws SAXParseException
        System.out.println("** Warning"
            + ", line " + err.getLineNumber()
            + ", uri " + err.getSystemId());
        System.out.println("   " + err.getMessage());
    }

    Just out of curiosity what happens if you append a space to the end of the XML document?

  • XML Document Merge

    Hi,
    I would like to merge(append) more than 1 XML documents into a single document.
    I'm trying to avoid using XSLT sofar and I gone through this forum and tried the following
    solution.
    Eg.,
    <!-- file1.xml -->
    <root>
    <Frthemes>
    <theme id="app1">
    <title name="French"/>
    </theme>
    </Frthemes>
    </root>
    <!-- file2.xml -->
    <root>
    <Enthemes>
    <theme id="doc" />
    <theme id="app1">
    <title name="English"/>
    <attrib x="1"/>
    </theme>
    </Enthemes>
    </root>
    After merging it should look like,
    <root>
    <Frthemes>
    <theme id="app1">
    <title name="French"/>
    </theme>
    </Frthemes>
    <Enthemes>
    <theme id="doc" />
    <theme id="app1">
    <title name="English"/>
    <attrib x="1"/>
    </theme>
    </Enthemes>
    </root>
    So I create a
    DocumentImpl myDoc;
    for (int i = 0; i < files.length; i++) {
    parser.parse(files.getCanonicalPath());
    myDoc = (DocumentImpl)parser.getDocument();
    mergeDocuments(newDoc, mibDoc.getDocumentElement());
    void mergeDocuments(Node parent, Node child) {
         // newDoc.appendChild(child);
    Node inserted = newDoc.importNode(child, true);
    parent.appendChild(inserted);
    either I get
    org.w3c.dom.DOMException: WRONG_DOCUMENT_ERR: A node is used in a different document than the one that created it.
    or
    org.w3c.dom.DOMException: HIERARCHY_REQUEST_ERR: If any node is inserted somewhere it doesn't belong
    Actually the interesting part is, I created a empty document and import a other node and it worked.
    Meaning, I can copy(merge) a document node into empty document.
    But If I try to merge doucument node into already existing document is gives WRONG_DOCUMENT_ERR
    So how do I merge more than 1 document with out using XSLT ?
    Using Xerces, Java1.4
    Thanks.

    try this
    Element element1 = doc1.getDocumentElement();
    Element element2 = doc2.getDocumentElement();
    // you gotta import the node into the right document
    Element tempElement = (Element) doc2.importNode(element1);
    element2.appendChild(tempElement);

  • Problem Digitally signing an xml document "Cannot resolve element"

    I am trying to sign a cXML document. I try to add 3 references to the XMLSignatureFactory but when it hits the 2nd on it throws an error "Cannot resolve element with ID cXMLData". How come I can't add more than 1?
    Here is the stack trace :
    java.lang.RuntimeException: javax.xml.crypto.dsig.XMLSignatureException: javax.xml.crypto.URIReferenceException: com.sun.org.apache.xml.internal.security.utils.res olver.ResourceResolverException: Cannot resolve element with ID cXMLData
    at com.praxair.security.b2b.CXMLDigitalSig.sign(CXMLD igitalSig.java:303)
    at com.praxair.security.b2b.CXMLDigitalSig.main(CXMLD igitalSig.java:359)
    Java Code:
    public class CXMLDigitalSig
         private XMLSignatureFactory factory;
         private KeyStore keyStore;
         private KeyPair keyPair;
         private KeyInfo keyInfo;
         private X509Certificate signingCert;
         public CXMLDigitalSig()
         private void loadCert() throws Exception
              //String keystoreFile = config.getString(KEY_STORE_FILE);
              //String password = config.getString(KEY_STORE_PASSWORD);
              //String alias = config.getString(KEY_STORE_ALIAS);
              String keystoreFile = "C:\\cxmlsign\\teststore";
              String password = "xxxxx";
              String alias = "xxxxx (thawte ssl ca)";
              keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
              File file = new File(keystoreFile);
              FileInputStream inStream = new FileInputStream(file);
              char [] passAsChar = password.toCharArray();          
              keyStore.load(inStream, passAsChar);
              inStream.close();
              String providerName = System.getProperty("jsr105Provider",
                        "org.jcp.xml.dsig.internal.dom.XMLDSigRI");
              factory = XMLSignatureFactory.getInstance("DOM", (Provider) Class
                        .forName(providerName).newInstance());
              KeyStore.PrivateKeyEntry entry = (KeyStore.PrivateKeyEntry) keyStore
                        .getEntry(alias, new KeyStore.PasswordProtection(passAsChar));
              signingCert = (X509Certificate) entry.getCertificate();
              keyPair = new KeyPair(entry.getCertificate().getPublicKey(),
                        entry.getPrivateKey());
              KeyInfoFactory kFactory = factory.getKeyInfoFactory();
              keyInfo = kFactory.newKeyInfo(Collections.singletonList(kFactory
                        .newX509Data(Collections.singletonList(entry
                                  .getCertificate()))));
          * This method returns the message digest for given certificate.
          * @param cert
          * @return
          * @throws NoSuchAlgorithmException
          * @throws CertificateEncodingException
         private static String getThumbPrint(X509Certificate cert)
                   throws NoSuchAlgorithmException, CertificateEncodingException {
              MessageDigest md = MessageDigest.getInstance("SHA-1");
              byte[] der = cert.getEncoded();
              md.update(der);
              byte[] digest = md.digest();
              return hexify(digest);
         private static String hexify(byte bytes[]) {
              char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                        'a', 'b', 'c', 'd', 'e', 'f' };
              StringBuffer buf = new StringBuffer(bytes.length * 2);
              for (int i = 0; i < bytes.length; ++i) {
                   buf.append(hexDigits[(bytes[i] & 0xf0) >> 4]);
                   buf.append(hexDigits[bytes[i] & 0x0f]);
              return buf.toString();
          * Adds an enveloped signature to the given document. The signature is
          * generated as per the CXML specfication outlined in the CXML user guide.
          * This method creates the signature and three references and also the XADES
          * information.
         public void sign(Element cxmlElement, String payloadId) throws SQLException {
              Reference ref1;
              Reference ref2;
              Reference ref3;
              List<Reference> refs = new ArrayList<Reference>();
              SignedInfo signedInfo;
              try {
                   ref1 = factory.newReference("#cXMLSignedInfo",
                             factory.newDigestMethod(DigestMethod.SHA1, null), null,
                             null, null);
                   refs.add(ref1);
                   ref2 = factory.newReference("#cXMLData",
                             factory.newDigestMethod(DigestMethod.SHA1, null), null,
                             null, null);
                   refs.add(ref2);
                   ref3 = factory.newReference("#XAdESSignedProps",
                             factory.newDigestMethod(DigestMethod.SHA1, null));
                   refs.add(ref3);
                   signedInfo = factory.newSignedInfo(factory
                             .newCanonicalizationMethod(
                                       CanonicalizationMethod.INCLUSIVE,
                                       (C14NMethodParameterSpec) null), factory
                             .newSignatureMethod(SignatureMethod.RSA_SHA1, null), refs);
              } catch (NoSuchAlgorithmException e) {
                   throw new RuntimeException(e);
              } catch (InvalidAlgorithmParameterException e) {
                   throw new RuntimeException(e);
              List<DOMStructure> xmlObjSignedInfo = new ArrayList<DOMStructure>();
              Element signedInfoElement = createElement(cxmlElement,
                        "cXMLSignedInfo", null, null);
              signedInfoElement.setAttributeNS(null, "Id", "cXMLSignedInfo");
              signedInfoElement.setAttributeNS(null, "payloadID", payloadId);
              signedInfoElement.setAttributeNS(null, "signatureVersion", "1.0");
              DOMStructure signedInfoStruct = new DOMStructure(signedInfoElement);
              xmlObjSignedInfo.add(signedInfoStruct);
              String xadesNS = "http://uri.etsi.org/01903/v1.1.1#";
              // Create the necessary XADES information as outlined in the CXML
              // specification
              Element QPElement = createElement(cxmlElement, "QualifyingProperties",
                        "xades", xadesNS);
              QPElement.setAttributeNS("http://www.w3.org/2000/xmlns/",
                        "xmlns:xades", xadesNS);
              QPElement.setAttributeNS(null, "Target", "#cXMLSignature");
              Element SPElement = createElement(cxmlElement, "SignedProperties",
                        "xades", xadesNS);
              SPElement.setAttributeNS(null, "Id", "XAdESSignedProps");
              IdResolver.registerElementById(SPElement, "XAdESSignedProps");
              QPElement.appendChild(SPElement);
              Element signedSPElement = createElement(cxmlElement,
                        "SignedSignatureProperties", "xades", xadesNS);
              Element signingTimeElement = createElement(cxmlElement, "SigningTime",
                        "xades", xadesNS);
              SimpleDateFormat dateFormatter = new SimpleDateFormat(
                        "yyyy-MM-dd'T'HH:mm:ss");
              signingTimeElement.appendChild(cxmlElement.getOwnerDocument()
                        .createTextNode(dateFormatter.format(new Date())));
              signedSPElement.appendChild(signingTimeElement);
              SPElement.appendChild(signedSPElement);
              String certDigest = "";
              try {
                   certDigest = getThumbPrint(signingCert);
              } catch (CertificateEncodingException ce) {
                   throw new RuntimeException(ce);
              } catch (NoSuchAlgorithmException ne) {
                   throw new RuntimeException(ne);
              Element signingCertificateElement = createElement(cxmlElement,
                        "SigningCertificate", "xades", xadesNS);
              Element certElement = createElement(cxmlElement, "Cert", "xades",
                        xadesNS);
              Element certDigestElement = createElement(cxmlElement, "CertDigest",
                        "xades", xadesNS);
              Element digestMethodElement = createElement(cxmlElement,
                        "DigestMethod", "ds", XMLSignature.XMLNS);
              digestMethodElement
                        .setAttributeNS(null, "Algorithm", DigestMethod.SHA1);
              Element digestValueElement = createElement(cxmlElement, "DigestValue",
                        "ds", XMLSignature.XMLNS);
              digestValueElement.appendChild(cxmlElement.getOwnerDocument()
                        .createTextNode(certDigest));
              Element issuerSerialElement = createElement(cxmlElement,
                        "IssuerSerial", "xades", xadesNS);
              Element x509IssuerNameElement = createElement(cxmlElement,
                        "X509IssuerName", "ds", XMLSignature.XMLNS);
              x509IssuerNameElement
                        .appendChild(cxmlElement.getOwnerDocument().createTextNode(
                                  signingCert.getIssuerX500Principal().toString()));
              Element x509IssuerSerialNumberElement = createElement(cxmlElement,
                        "X509IssuerSerialNumber", "ds", XMLSignature.XMLNS);
              x509IssuerSerialNumberElement.appendChild(cxmlElement
                        .getOwnerDocument().createTextNode(
                                  signingCert.getSerialNumber().toString()));
              certDigestElement.appendChild(digestMethodElement);
              certDigestElement.appendChild(digestValueElement);
              certElement.appendChild(certDigestElement);
              issuerSerialElement.appendChild(x509IssuerNameElement);
              issuerSerialElement.appendChild(x509IssuerSerialNumberElement);
              certElement.appendChild(issuerSerialElement);
              signingCertificateElement.appendChild(certElement);
              signedSPElement.appendChild(signingCertificateElement);
              DOMStructure qualifPropStruct = new DOMStructure(QPElement);
              List<DOMStructure> xmlObjQualifyingProperty = new ArrayList<DOMStructure>();
              xmlObjQualifyingProperty.add(qualifPropStruct);
              XMLObject objectSingedInfo = factory.newXMLObject(xmlObjSignedInfo,
                        null, null, null);
              XMLObject objectQualifyingProperty = factory.newXMLObject(
                        xmlObjQualifyingProperty, null, null, null);
              // Create the ds:object tags
              List<XMLObject> objects = new ArrayList<XMLObject>();
              objects.add(objectSingedInfo);
              objects.add(objectQualifyingProperty);
              XMLSignature signature = factory.newXMLSignature(signedInfo, keyInfo,
                        objects, "cXMLSignature", null);
              DOMSignContext signContext = new DOMSignContext(keyPair.getPrivate(),
                        cxmlElement);
              signContext.putNamespacePrefix(XMLSignature.XMLNS, "ds");
              try {
                   signature.sign(signContext);
              } catch (MarshalException e) {
                   throw new RuntimeException(e);
              } catch (XMLSignatureException e) {
                   throw new RuntimeException(e);
         private Element createElement(Element element, String tag, String prefix,
                   String nsURI) {
              String qName = prefix == null ? tag : prefix + ":" + tag;
              return element.getOwnerDocument().createElementNS(nsURI, qName);
         X509Certificate getSigningCert() {
              return signingCert;
         private static String readFileAsString(String filePath)     throws java.io.IOException
              byte[] buffer = new byte[(int) new File(filePath).length()];
              BufferedInputStream f = null;
              try {
                   f = new BufferedInputStream(new FileInputStream(filePath));
                   f.read(buffer);
              } finally {
                   if (f != null) {
                        try {
                             f.close();
                        } catch (IOException ignored) {
              return new String(buffer);
         public static void main(String args[])
              System.out.println("start");
              CXMLDigitalSig cXMLDigitalSig = new CXMLDigitalSig();
              try
                   cXMLDigitalSig.loadCert();
                      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                      dbf.setNamespaceAware(true);
                   String cXML = readFileAsString("C:\\cxmlsign\\cxml.xml");
                      Document cxmlDocument = dbf.newDocumentBuilder()
                                                 .parse(new ByteArrayInputStream(cXML
                                                           .getBytes("UTF-8")));
                   System.out.println(cxmlDocument.getDocumentElement().getTagName());
                      cXMLDigitalSig.sign(cxmlDocument.getDocumentElement(), "55");
              catch(Exception e)
                   //System.out.println(e.getMessage());
                   System.out.println(getStackTrace(e));
                 System.out.println("end");
           public static String getStackTrace(Throwable aThrowable) {
                  final Writer result = new StringWriter();
                  final PrintWriter printWriter = new PrintWriter(result);
                  aThrowable.printStackTrace(printWriter);
                  return result.toString();
    }Edited by: sabre150 on Jan 18, 2012 1:57 PM
    Moderator action : added [ code ] tags to format source code

    I am trying to sign a cXML document. I try to add 3 references to the XMLSignatureFactory but when it hits the 2nd on it throws an error "Cannot resolve element with ID cXMLData". How come I can't add more than 1?
    Here is the stack trace :
    java.lang.RuntimeException: javax.xml.crypto.dsig.XMLSignatureException: javax.xml.crypto.URIReferenceException: com.sun.org.apache.xml.internal.security.utils.res olver.ResourceResolverException: Cannot resolve element with ID cXMLData
    at com.praxair.security.b2b.CXMLDigitalSig.sign(CXMLD igitalSig.java:303)
    at com.praxair.security.b2b.CXMLDigitalSig.main(CXMLD igitalSig.java:359)
    Java Code:
    public class CXMLDigitalSig
         private XMLSignatureFactory factory;
         private KeyStore keyStore;
         private KeyPair keyPair;
         private KeyInfo keyInfo;
         private X509Certificate signingCert;
         public CXMLDigitalSig()
         private void loadCert() throws Exception
              //String keystoreFile = config.getString(KEY_STORE_FILE);
              //String password = config.getString(KEY_STORE_PASSWORD);
              //String alias = config.getString(KEY_STORE_ALIAS);
              String keystoreFile = "C:\\cxmlsign\\teststore";
              String password = "xxxxx";
              String alias = "xxxxx (thawte ssl ca)";
              keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
              File file = new File(keystoreFile);
              FileInputStream inStream = new FileInputStream(file);
              char [] passAsChar = password.toCharArray();          
              keyStore.load(inStream, passAsChar);
              inStream.close();
              String providerName = System.getProperty("jsr105Provider",
                        "org.jcp.xml.dsig.internal.dom.XMLDSigRI");
              factory = XMLSignatureFactory.getInstance("DOM", (Provider) Class
                        .forName(providerName).newInstance());
              KeyStore.PrivateKeyEntry entry = (KeyStore.PrivateKeyEntry) keyStore
                        .getEntry(alias, new KeyStore.PasswordProtection(passAsChar));
              signingCert = (X509Certificate) entry.getCertificate();
              keyPair = new KeyPair(entry.getCertificate().getPublicKey(),
                        entry.getPrivateKey());
              KeyInfoFactory kFactory = factory.getKeyInfoFactory();
              keyInfo = kFactory.newKeyInfo(Collections.singletonList(kFactory
                        .newX509Data(Collections.singletonList(entry
                                  .getCertificate()))));
          * This method returns the message digest for given certificate.
          * @param cert
          * @return
          * @throws NoSuchAlgorithmException
          * @throws CertificateEncodingException
         private static String getThumbPrint(X509Certificate cert)
                   throws NoSuchAlgorithmException, CertificateEncodingException {
              MessageDigest md = MessageDigest.getInstance("SHA-1");
              byte[] der = cert.getEncoded();
              md.update(der);
              byte[] digest = md.digest();
              return hexify(digest);
         private static String hexify(byte bytes[]) {
              char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                        'a', 'b', 'c', 'd', 'e', 'f' };
              StringBuffer buf = new StringBuffer(bytes.length * 2);
              for (int i = 0; i < bytes.length; ++i) {
                   buf.append(hexDigits[(bytes[i] & 0xf0) >> 4]);
                   buf.append(hexDigits[bytes[i] & 0x0f]);
              return buf.toString();
          * Adds an enveloped signature to the given document. The signature is
          * generated as per the CXML specfication outlined in the CXML user guide.
          * This method creates the signature and three references and also the XADES
          * information.
         public void sign(Element cxmlElement, String payloadId) throws SQLException {
              Reference ref1;
              Reference ref2;
              Reference ref3;
              List<Reference> refs = new ArrayList<Reference>();
              SignedInfo signedInfo;
              try {
                   ref1 = factory.newReference("#cXMLSignedInfo",
                             factory.newDigestMethod(DigestMethod.SHA1, null), null,
                             null, null);
                   refs.add(ref1);
                   ref2 = factory.newReference("#cXMLData",
                             factory.newDigestMethod(DigestMethod.SHA1, null), null,
                             null, null);
                   refs.add(ref2);
                   ref3 = factory.newReference("#XAdESSignedProps",
                             factory.newDigestMethod(DigestMethod.SHA1, null));
                   refs.add(ref3);
                   signedInfo = factory.newSignedInfo(factory
                             .newCanonicalizationMethod(
                                       CanonicalizationMethod.INCLUSIVE,
                                       (C14NMethodParameterSpec) null), factory
                             .newSignatureMethod(SignatureMethod.RSA_SHA1, null), refs);
              } catch (NoSuchAlgorithmException e) {
                   throw new RuntimeException(e);
              } catch (InvalidAlgorithmParameterException e) {
                   throw new RuntimeException(e);
              List<DOMStructure> xmlObjSignedInfo = new ArrayList<DOMStructure>();
              Element signedInfoElement = createElement(cxmlElement,
                        "cXMLSignedInfo", null, null);
              signedInfoElement.setAttributeNS(null, "Id", "cXMLSignedInfo");
              signedInfoElement.setAttributeNS(null, "payloadID", payloadId);
              signedInfoElement.setAttributeNS(null, "signatureVersion", "1.0");
              DOMStructure signedInfoStruct = new DOMStructure(signedInfoElement);
              xmlObjSignedInfo.add(signedInfoStruct);
              String xadesNS = "http://uri.etsi.org/01903/v1.1.1#";
              // Create the necessary XADES information as outlined in the CXML
              // specification
              Element QPElement = createElement(cxmlElement, "QualifyingProperties",
                        "xades", xadesNS);
              QPElement.setAttributeNS("http://www.w3.org/2000/xmlns/",
                        "xmlns:xades", xadesNS);
              QPElement.setAttributeNS(null, "Target", "#cXMLSignature");
              Element SPElement = createElement(cxmlElement, "SignedProperties",
                        "xades", xadesNS);
              SPElement.setAttributeNS(null, "Id", "XAdESSignedProps");
              IdResolver.registerElementById(SPElement, "XAdESSignedProps");
              QPElement.appendChild(SPElement);
              Element signedSPElement = createElement(cxmlElement,
                        "SignedSignatureProperties", "xades", xadesNS);
              Element signingTimeElement = createElement(cxmlElement, "SigningTime",
                        "xades", xadesNS);
              SimpleDateFormat dateFormatter = new SimpleDateFormat(
                        "yyyy-MM-dd'T'HH:mm:ss");
              signingTimeElement.appendChild(cxmlElement.getOwnerDocument()
                        .createTextNode(dateFormatter.format(new Date())));
              signedSPElement.appendChild(signingTimeElement);
              SPElement.appendChild(signedSPElement);
              String certDigest = "";
              try {
                   certDigest = getThumbPrint(signingCert);
              } catch (CertificateEncodingException ce) {
                   throw new RuntimeException(ce);
              } catch (NoSuchAlgorithmException ne) {
                   throw new RuntimeException(ne);
              Element signingCertificateElement = createElement(cxmlElement,
                        "SigningCertificate", "xades", xadesNS);
              Element certElement = createElement(cxmlElement, "Cert", "xades",
                        xadesNS);
              Element certDigestElement = createElement(cxmlElement, "CertDigest",
                        "xades", xadesNS);
              Element digestMethodElement = createElement(cxmlElement,
                        "DigestMethod", "ds", XMLSignature.XMLNS);
              digestMethodElement
                        .setAttributeNS(null, "Algorithm", DigestMethod.SHA1);
              Element digestValueElement = createElement(cxmlElement, "DigestValue",
                        "ds", XMLSignature.XMLNS);
              digestValueElement.appendChild(cxmlElement.getOwnerDocument()
                        .createTextNode(certDigest));
              Element issuerSerialElement = createElement(cxmlElement,
                        "IssuerSerial", "xades", xadesNS);
              Element x509IssuerNameElement = createElement(cxmlElement,
                        "X509IssuerName", "ds", XMLSignature.XMLNS);
              x509IssuerNameElement
                        .appendChild(cxmlElement.getOwnerDocument().createTextNode(
                                  signingCert.getIssuerX500Principal().toString()));
              Element x509IssuerSerialNumberElement = createElement(cxmlElement,
                        "X509IssuerSerialNumber", "ds", XMLSignature.XMLNS);
              x509IssuerSerialNumberElement.appendChild(cxmlElement
                        .getOwnerDocument().createTextNode(
                                  signingCert.getSerialNumber().toString()));
              certDigestElement.appendChild(digestMethodElement);
              certDigestElement.appendChild(digestValueElement);
              certElement.appendChild(certDigestElement);
              issuerSerialElement.appendChild(x509IssuerNameElement);
              issuerSerialElement.appendChild(x509IssuerSerialNumberElement);
              certElement.appendChild(issuerSerialElement);
              signingCertificateElement.appendChild(certElement);
              signedSPElement.appendChild(signingCertificateElement);
              DOMStructure qualifPropStruct = new DOMStructure(QPElement);
              List<DOMStructure> xmlObjQualifyingProperty = new ArrayList<DOMStructure>();
              xmlObjQualifyingProperty.add(qualifPropStruct);
              XMLObject objectSingedInfo = factory.newXMLObject(xmlObjSignedInfo,
                        null, null, null);
              XMLObject objectQualifyingProperty = factory.newXMLObject(
                        xmlObjQualifyingProperty, null, null, null);
              // Create the ds:object tags
              List<XMLObject> objects = new ArrayList<XMLObject>();
              objects.add(objectSingedInfo);
              objects.add(objectQualifyingProperty);
              XMLSignature signature = factory.newXMLSignature(signedInfo, keyInfo,
                        objects, "cXMLSignature", null);
              DOMSignContext signContext = new DOMSignContext(keyPair.getPrivate(),
                        cxmlElement);
              signContext.putNamespacePrefix(XMLSignature.XMLNS, "ds");
              try {
                   signature.sign(signContext);
              } catch (MarshalException e) {
                   throw new RuntimeException(e);
              } catch (XMLSignatureException e) {
                   throw new RuntimeException(e);
         private Element createElement(Element element, String tag, String prefix,
                   String nsURI) {
              String qName = prefix == null ? tag : prefix + ":" + tag;
              return element.getOwnerDocument().createElementNS(nsURI, qName);
         X509Certificate getSigningCert() {
              return signingCert;
         private static String readFileAsString(String filePath)     throws java.io.IOException
              byte[] buffer = new byte[(int) new File(filePath).length()];
              BufferedInputStream f = null;
              try {
                   f = new BufferedInputStream(new FileInputStream(filePath));
                   f.read(buffer);
              } finally {
                   if (f != null) {
                        try {
                             f.close();
                        } catch (IOException ignored) {
              return new String(buffer);
         public static void main(String args[])
              System.out.println("start");
              CXMLDigitalSig cXMLDigitalSig = new CXMLDigitalSig();
              try
                   cXMLDigitalSig.loadCert();
                      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                      dbf.setNamespaceAware(true);
                   String cXML = readFileAsString("C:\\cxmlsign\\cxml.xml");
                      Document cxmlDocument = dbf.newDocumentBuilder()
                                                 .parse(new ByteArrayInputStream(cXML
                                                           .getBytes("UTF-8")));
                   System.out.println(cxmlDocument.getDocumentElement().getTagName());
                      cXMLDigitalSig.sign(cxmlDocument.getDocumentElement(), "55");
              catch(Exception e)
                   //System.out.println(e.getMessage());
                   System.out.println(getStackTrace(e));
                 System.out.println("end");
           public static String getStackTrace(Throwable aThrowable) {
                  final Writer result = new StringWriter();
                  final PrintWriter printWriter = new PrintWriter(result);
                  aThrowable.printStackTrace(printWriter);
                  return result.toString();
    }Edited by: sabre150 on Jan 18, 2012 1:57 PM
    Moderator action : added [ code ] tags to format source code

Maybe you are looking for

  • Windows 8.1 Update 1 (Spring update KB2919355) - User Profile Service failed the sign-in

    After installing Windows 8.1 Update 1 (Spring update KB2919355), our enterprise  Windows 8.1 image began getting User Profile Service failed the sign-in. Uninstalling the update fixes the issue. The update somehow modifies the default user profile ca

  • Can i download multiple copies of mountain lion to my other mac's?

    I purchsed a copy of Mountain lion from the app store and downloaded it to my laptop.  my son purchased a copy of it and downloaded it to his laptop...it made me think that maybe....just maybe i don't have to purchase 3 other copies for each of our f

  • Best Practice for SRST deployment at a remote site

    What is the best practice for a SRST deployment at a remote site? Should a separate router such as a 3800 series be deployed for telephony in addition to another router to be deployed for Data? Is there a need for 2 different devices?

  • Installment based payment terms

    SAP Gurus, Can you please tell me how to create installment based payment terms in sap. With any situable scenario...... Regards.

  • Handling showBusyCursor event...

    Hi everyone, it's me again... On my application I do the comunication with Java via RemoteObject and the method of the RemoteObject has the property showBusyCursor... I need that when the busyCursor is active the Application is unable... but i can't