Insert XML String into XML file at a certain position

Hello,
I have this xml string:
<jdbc-driver-params>
<url>jdbc:oracle:thin:@localhost:1521:mydb</url>
<driver-name>oracle.jdbc.OracleDriver</driver-name>
<properties>
<property>
<name>user</name>
<value>myuser</value>
</property>
</properties>
<password-encrypted>myuser</password-encrypted>
</jdbc-driver-params>and i need to insert it into an xml file at a certain position (as child for a node)
The xml file looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<jdbc-data-source xmlns="http://www.bea.com/ns/weblogic/90"
    xmlns:sec="http://www.bea.com/ns/weblogic/90/security"
    xmlns:wls="http://www.bea.com/ns/weblogic/90/security/wls"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.bea.com/ns/weblogic/920 http://www.bea.com/ns/weblogic/920.xsd">
    <name>myDB</name>
    <jdbc-data-source-params>
        <global-transactions-protocol>OnePhaseCommit</global-transactions-protocol>
    </jdbc-data-source-params>
</jdbc-data-source>And this is how I would like to get it in the end:
<?xml version='1.0' encoding='UTF-8'?>
<jdbc-data-source xmlns="http://www.bea.com/ns/weblogic/90" xmlns:sec="http://www.bea.com/ns/weblogic/90/security" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:wls="http://www.bea.com/ns/weblogic/90/security/wls" xsi:schemaLocation="http://www.bea.com/ns/weblogic/920 http://www.bea.com/ns/weblogic/920.xsd">
  <name>mydb</name>
  <jdbc-driver-params>
    <url>jdbc:oracle:thin:@localhost:1521:myDB</url>
    <driver-name>oracle.jdbc.OracleDriver</driver-name>
    <properties>
      <property>
        <name>user</name>
        <value>myuser</value>
      </property>
    </properties>
    <password-encrypted>myuser</password-encrypted>
  </jdbc-driver-params>
  <jdbc-connection-pool-params>
    <test-table-name>SQL SELECT 1 FROM DUAL</test-table-name>
  </jdbc-connection-pool-params>
  <jdbc-data-source-params>
    <global-transactions-protocol>OnePhaseCommit</global-transactions-protocol>
  </jdbc-data-source-params>
</jdbc-data-source>So, I obtain the node for the given xml string, the jdbc-data-source node from the xml file and i attempt the appendChild. The problem is that nothing really gets inserted into the xml file.
Someone, any idea?
My code:
try
               DOMParser parser = new DOMParser();
               parser.parse(xmlFileName);
               Document doc = parser.getDocument(); // the document we will insert node into
               Node root = doc.getElementsByTagName("jdbc-data-source").item(0);
               //get XML string node
               DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
               DocumentBuilder db = factory.newDocumentBuilder();
               InputSource inStream = new InputSource();
               inStream.setCharacterStream(new StringReader(xmlString));
               Document doc4XMLString = db.parse(inStream);
               Node rootXMLString = doc4XMLString.getElementsByTagName("jdbc-driver-params").item(0);
               root.appendChild(doc.importNode(rootXMLString, true));
               return true;
          catch (Exception e)
               e.printStackTrace();
          }Thanks,
johnny
Edited by: smeag0l on Aug 6, 2008 5:08 PM
Edited by: smeag0l on Aug 6, 2008 5:43 PM

Well, you helped me again :-) Thank you very much!
Here is how the code should look:
                        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
               DocumentBuilder db4XMLFile = factory.newDocumentBuilder();
               Document doc4XMLFile = db4XMLFile.parse(xmlFileName);
               Node root4XMLFile = doc4XMLFile.getElementsByTagName(rootNodeName).item(0);
               DocumentBuilder db4XMLString = factory.newDocumentBuilder();
               InputSource inStream = new InputSource();
               inStream.setCharacterStream(new StringReader(xmlString));
               Document doc4XMLString = db4XMLString.parse(inStream);
               Node root4XMLString = doc4XMLString.getElementsByTagName(xmlStringNodeName).item(0);
               root4XMLFile.appendChild(doc4XMLFile.importNode(root4XMLString, true));
               File file = new File(xmlFileName);
                        Result result = new StreamResult(file.toURI().getPath());
               Source source = new DOMSource(doc4XMLFile);
               Transformer xformer = TransformerFactory.newInstance().newTransformer();
                  xformer.transform(source, result);

Similar Messages

  • Convert XML string into XML

    Hi All,
    Can you please let me know for any sample code in xslt/java mapping for converting XML string into XML. We use SAP Pi 7.0
    My XML string starts like this
    <?xml version="1.0" encoding="UTF-8" ?> 
    - <ns0:MT_ReceiverFileStructure <namespace>"><Output><?xml version="1.0" encoding="ISO-8859-9"?><?xml-stylesheet type="text/xsl" href="<xsl>"?><Tarih_Date Tarih="11.09.2014" Date="09/11/2014>
       Thanks,
       Pavithra

    Thanks Praveen. It worked.
    However, the xml i have is an extract from a exchange rate URL and it has the reference to a xsl in it as below
    <?xml version="1.0" encoding="ISO-8859-9"?><?xml-stylesheet type="text/xsl" href="<ABC.xsl>"?>.
    So there is an error in sxmb_moni. Is it possible to remove this.

  • REG: WRITE XML STRING INTO XML FILE

    Hi All, I have a XML FILE on PC. I get a xml string from my server.
    My Task: I want to append the xml string coming from the server into the existing xml file at a particular Node. Given below is my code :
    String xmlString = baos.toString();
                      DocumentBuilder db4XMLString = docBuilderFactory.newDocumentBuilder();
                      InputSource inStream = new InputSource();
                      inStream.setCharacterStream(new StringReader(xmlString));
                      Document doc4XMLString = db4XMLString.parse(inStream);
                      Node root4XMLString = doc4XMLString.getElementsByTagName("epg").item(0);
                      doc.appendChild(doc.importNode(root4XMLString, true));
                      File file = new File(Constant.XMLFILEPATH);
                      Result result = new StreamResult(file.toURI().getPath());
                      Source source = new DOMSource(doc);
                      Transformer xformer = TransformerFactory.newInstance().newTransformer();
                      xformer.transform(source, result);But, wen i run my application I get following exception:
    The markup in the document following the root element must be well-formed.
    org.xml.sax.SAXParseException: The markup in the document following the root element must be well-formed.
    at org.apache.xerces.parsers.DOMParser.parse(Unknown Source)
    at org.apache.xerces.jaxp.DocumentBuilderImpl.parse(Unknown Source)
    Is that my XML string is not well formed. Is it so then please let me how to convert my xml string into well formed XML data.
    Please help me out.
    Thanking You.

    There are many reasons why xmlString could be not well formed. There is no magic recipe for making it well formed: just look at it and see why it is not parseable.
    Note that this line:
    String xmlString = baos.toString();can be problematic if you have non ASCII-7 characters in your XML document. baos could then contain a byte representation of these characters in one particular encoding, but, since you use the .toString() method that relies on the default encoding of your system, you can end up with a mismatch and garbage in your XML.

  • Convert xml string into xml file?

    Hi,
    I got a method that returns an JDom Element object.
    Then I use the JDOM Element toString method() to change it into xml string.
    Now, I need to convert it into actual xml file.
    How to I do it?
    Thanks.

    Hi,
    If you got an xml string, just write it to an ordinary file. Look at FileWriter.
    /Kaj

  • A class to format an XML string into indented xml code

    I am looking for a class or a piece of code to format an XML string into indented xml code
    for example: an XML string as follows
    <servlet><servlet-name>Login</servlet-name>servlet-class>ucs.merch.client.system.LoginServlet</servlet-class></servlet><servlet-mapping><servlet-name>Login</servlet-name>
    to format into :
    <servlet>
    <servlet-name>Login</servlet-name>
    <servlet-class>ucs.merch.client.system.LoginServlet</servlet-class>
    </servlet>
    <servlet-mapping>
    <servlet-name>Login</servlet-name>
    <url-pattern>/Login</url-pattern>
    </servlet-mapping>
    e-mail : [email protected]

    Xerces has a class called OutputFormat
    If you have your XML document in memory, you can format it using the method setIndenting(true) on the OutputFormat class. The following is an example:
    assuming xmlDoc is our document and fileName is the name of the file we wish to write to:
    OutputFormat format = new OutputFormat(xmlDoc);
    // setup output file name
    PrintWriter printwriter = new PrintWriter(new FileWriter(fileName, false));
    // construct an XMLSerializer for writing the document
    XMLSerializer serializer = new XMLSerializer( printwriter, format );
    // Ensure output is indented correctly...
    format.setIndenting(true);
    // set serializer as a DOM Serializer
    serializer.asDOMSerializer();
    // serialize the document
    serializer.serialize(xmlDoc);
    hope this helps!
    Rob.

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

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

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

  • How to convert Java string into XML one?

    With SAX I can parse an xml file, but I should create xml file by hands.
    Ok, it's simple, but how to encode java string into XML constant
    like "Hello & goodby" into "Hello & goodby" ?
    Is there a standard method for such special xml characters?

    If you are creating your XML "by hand" then just make sure your hands know that you have to do that. It isn't difficult to write a Java method to do it, if "by hand" means "in Java code". Otherwise your XML is not well-formed. And as far as I know there is no package that takes ill-formed XML and fixes it up.

  • Conversion of xml string to xml file

    To convert xml string to xml file in java i used
    Document XMLDoc=DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new StringReader("<root><main>Title</main></root&g t;")));
    But it is showing an error as InputSource cannot be resolved
    How to rectify this

    I assume you mean there is a compiler error? (It helps if you explain your problem instead of just giving a vague description of it.) It sounds like you have to import InputSource. You do know about the import statements that go at the beginning of a Java class, don't you?

  • Create Business Partner from XMl String not a file

    Hi,
    Is it possible to create a BP from an XML string. 
    I know about GetBusinessPartnerFromXml(string FileName, int index)
    but I dont want to save the string in a file before creating a BP from it
    Hope there's a method to do that

    Marc,
    This looks like it is a duplicate of this post, so I am closing this thread as it looks like you answered your own question!
    Create Business Partner from XMl String not a file
    Eddy

  • Convert XML string into DOM

    Hi all,
    I have a question here regarding converting XML string into a DOM document.
    How can I do this in Java?
    The Document.Parse() methods do not have one that takes in String as its parameter.
    I'm not sure what is the best way to do this in Java.
    Any help is greatly appreciated.
    Thank you in advance.
    regards,
    Sean

    Convert XML String to Document with StringReader.
    String xmlString;
    DocumentBuilderFactory factory =
                DocumentBuilderFactory.newInstance();
                DocumentBuilder builder = factory.newDocumentBuilder();
       Document         document = builder.parse(new InputSource(new StringReader(xmlString)));

  • Convert string into XML inside BPEL

    Hello ,
    How to convert string into xml format ? And make element and define attribute inside it ??

    There are several problems with your input:
    1. Your xml is not well-formed because the attribute values should be enclosed withing double " quotes and not single ' quotes;
    2. You use a prefix (sml) for the folowing part but you dont define the namespace:
    <ids>
    <VID ID="new"/>
    <data>
    <*sml:*attr name="std">
    <sml:value></sml:value>
    </sml:attr>
    <sml:attr name="xde">
    <sml:value></sml:value>
    </sml:attr>
    </data>
    </ids>
    Complete message should be:
    <ids xmlns:sml="somenamespace">
    <VID ID="new"/>
    <data>
    <sml:attr name="std">
    <sml:value></sml:value>
    </sml:attr>
    <sml:attr name="xde">
    <sml:value></sml:value>
    </sml:attr>
    </data>
    </ids>
    3. Do you assign this expression to a variable that is based on the schema of your message you want to parse
    Regards,
    Melvin
    * TIP Answer the question as helpful or correct if it helps you , so that someone else will be knowing that this solution helped you or worked for you and also it gives points to the person who answers the question. *

  • Convert XML string into an abap format date and time

    Hi,
    Does anyone know of a method or a function module in ABAP which converts XML string into an abap format date and time.
    Here is a part of the xml that I want to convert.
    <ns2:EventDateTime>2009-07-02T10:13:45+10:00</ns2:EventDateTime>
    <ns2:EventMessageTransmissionDateTime>2009-07-02T10:13:45.987+10:00</ns2:EventMessageTransmissionDateTime>
    Currently EventDateTime and EventMessageTransmissionDateTime are type XSDDATETIME_Z and these are converted to proper dates and times. We will be changing these fields to a STRING instead of XSDDATETIME_Z. The reason for this is to make the field more versatile. The customer would be receiving dates with Zulu (2009-09-23T12:00:00Z), with offsets (2009-09-23T12:00:00+10:00/-10:00) and just local timestamp (2009-09-23T12:00:00). With this, we need to make the date fields as string
    to be able to accept the various date formats (esp. the local timestamp).
    I am looking for a standard function module or method that will convert the xml string to a proper date and time abap format.
    Would appreciate anyone's help!
    Thanks.
    Edited by: eunice ocson on Jul 13, 2009 1:49 AM
    Edited by: eunice ocson on Jul 13, 2009 1:50 AM
    Edited by: eunice ocson on Jul 13, 2009 1:51 AM
    Edited by: eunice ocson on Jul 13, 2009 1:51 AM

    Hi Eunice
    Use the FM 'SMUM_XML_PARSE'
    for more info
    [Convert XML string to ABAP|XML String to ABAP or GUI]
    hope it helps you.
    Thanks!!

  • XML string to XML parsing in JCD

    I have stored an XML file as a CLOB in the Oracle DB. While fetching this data into JCD using Oracle OTD, I am getting this CLOB field as a string containing the XML. Now I want to parse this XML string to XML, as I need to map the individual fields to an XSD OTD, which will be my output.
    Kindly suggest a way to achieve this.

    An XSD OTD has an unmarshalFromString() method:
    inputFormat.unmarshalFromString( strData );
    When putting the XML into the CLOB it could be a good idea to wrap an outputstream into a Writer object in order to make certain that the encoding is correct, depending how the data is represented. When retrieving CLOB data using getCharacterStream() you will get a Reader object where the encoding is already given.

  • Got error message when store XML documents into XML DB repository, via WebD

    Hi experts,
    I am in I am in Oracle Enterprise Manager 11g 11.2.0.1.0.
    SQL*Plus: Release 11.2.0.1.0 Production on Tue Feb 22 11:40:23 2011
    I got error message when store XML documents into XML DB repository, via WebDAV.
    I have successfully registered 5 related schemas and generated 1 table.
    I have inserted 40 .xml files into this auto generated table.
    using these data I created relational view successfully.
    but since I couldn't store XML documents into XML DB repository, via WebDAV
    when I query using below code:
    SELECT rv.res.getClobVal()
    FROM resource_view rv
    WHERE rv.any_path = '/home/DEV/messages/4fe1-865d-da0db9212f34.xml';
    I got nothing.
    My ftp code is listed below:
    ftp> open localhost 2100
    Connected to I0025B368E2F9.
    220- C0025B368E2F9
    Unauthorised use of this FTP server is prohibited and may be subject to civil and criminal prosecution.
    220 I0025B368E2F9 FTP Server (Oracle XML DB/Oracle Database) ready.
    User (I0025B368E2F9:(none)): fda_xml
    331 pass required for FDA_XML
    Password:
    230 FDA_XML logged in
    ftp> cd /home/DEV/message
    250 CWD Command successful
    ftp> pwd
    257 "/home/DEV/message" is current directory.
    ftp> ls -la
    200 PORT Command successful
    150 ASCII Data Connection
    drw-r--r-- 2 FDA_XML oracle 0 DEC 17 19:19 .
    drw-r--r-- 2 FDA_XML oracle 0 DEC 17 19:19 ..
    226 ASCII Transfer Complete
    ftp: 115 bytes received in 0.00Seconds 115000.00Kbytes/sec.
    250 SET_CHARSET Command Successful
    ftp> put C:\ED\SPL\E_Reon_Data\loaded\4fe1-865d-da0db9212f34.xml
    200 PORT Command successful
    150 ASCII Data Connection
    550- Error Response
    ORA-00600: internal error code, arguments: [qmxConvUnkType], [], [], [], [], [], [], [], [], [], [], []
    550 End Error Response
    ftp: 3394 bytes sent in 0.00Seconds 3394000.00Kbytes/sec.
    I have tried all suggestion from another thread such as:
    alter system set events ='31150 trace name context forever, level 0x4000'
    SQL> alter system set shared_servers = 1;
    but failed.
    is there anyone can help?
    Thanks.
    Edited by: Cow on Mar 29, 2011 12:58 AM

    Hi experts,
    I am in I am in Oracle Enterprise Manager 11g 11.2.0.1.0.
    SQL*Plus: Release 11.2.0.1.0 Production on Tue Feb 22 11:40:23 2011
    I got error message when store XML documents into XML DB repository, via WebDAV.
    I have successfully registered 5 related schemas and generated 1 table.
    I have inserted 40 .xml files into this auto generated table.
    using these data I created relational view successfully.
    but since I couldn't store XML documents into XML DB repository, via WebDAV
    when I query using below code:
    SELECT rv.res.getClobVal()
    FROM resource_view rv
    WHERE rv.any_path = '/home/DEV/messages/4fe1-865d-da0db9212f34.xml';
    I got nothing.
    My ftp code is listed below:
    ftp> open localhost 2100
    Connected to I0025B368E2F9.
    220- C0025B368E2F9
    Unauthorised use of this FTP server is prohibited and may be subject to civil and criminal prosecution.
    220 I0025B368E2F9 FTP Server (Oracle XML DB/Oracle Database) ready.
    User (I0025B368E2F9:(none)): fda_xml
    331 pass required for FDA_XML
    Password:
    230 FDA_XML logged in
    ftp> cd /home/DEV/message
    250 CWD Command successful
    ftp> pwd
    257 "/home/DEV/message" is current directory.
    ftp> ls -la
    200 PORT Command successful
    150 ASCII Data Connection
    drw-r--r-- 2 FDA_XML oracle 0 DEC 17 19:19 .
    drw-r--r-- 2 FDA_XML oracle 0 DEC 17 19:19 ..
    226 ASCII Transfer Complete
    ftp: 115 bytes received in 0.00Seconds 115000.00Kbytes/sec.
    250 SET_CHARSET Command Successful
    ftp> put C:\ED\SPL\E_Reon_Data\loaded\4fe1-865d-da0db9212f34.xml
    200 PORT Command successful
    150 ASCII Data Connection
    550- Error Response
    ORA-00600: internal error code, arguments: [qmxConvUnkType], [], [], [], [], [], [], [], [], [], [], []
    550 End Error Response
    ftp: 3394 bytes sent in 0.00Seconds 3394000.00Kbytes/sec.
    I have tried all suggestion from another thread such as:
    alter system set events ='31150 trace name context forever, level 0x4000'
    SQL> alter system set shared_servers = 1;
    but failed.
    is there anyone can help?
    Thanks.
    Edited by: Cow on Mar 29, 2011 12:58 AM

  • XML String to XML Parsing

    I have stored an XML file as a CLOB in the Oracle DB. While fetching this data into JCD in JavaCAPS using Oracle OTD, I am getting this CLOB field as a string containing the XML. Now I want to parse this XML string to XML, as I need to map the individual fields to an XSD OTD, which will be my output.
    Kindly suggest a way to achieve this.

    The forum itself is a good starting point : [http://forum.java.sun.com/thread.jspa?forumID=34&threadID=347151] is a result searching for "parse string"...

Maybe you are looking for

  • Password no longer works in administrator account.

    Did an Archive and Install upgrade to Leopard without a problem. All Apps seem to work OK. In Preferences/Accounts I am still listed as administrator, but when I try to shut down or do other administrator chores I get an invalid user or password erro

  • HP Touchpad "Unknown Error" when trying to login to Google account

    Hello! When i try to login to Google on HP Touchpad i get a "Unknown Error" I have tried: 1) Restarting Touchpad 2) Checking (& Installing) All Updates 3) Changing Google Password None Of These Work! My Google account password has no special charecte

  • How can i tell if my iphone4 has a virus?

    How can I find out if my iphone 4s has a virus?

  • Alternative external hard drive solution now that FW is gone?

    Okay, so I purchased my new Macbook without totally thinking through the implications of the lack of FW. I'm now using this shiny new computer and went to do a first time backup after reinstalling applications and files manually (I've had some softwa

  • Scam messages purpurted to be from Verizon

    I received a phone call from 732-430-5603 claiming to be from Verizon, and telling me that my phone line was going to be disconnected for not paying my bill in time.  Since I know I am up to date on my Verizon payments, I asked the caller to identify