String to XML

Hi everyone,
i'm just writing a method, that gets a string and a XPath and want writes the string to the specific XPath in my xml document. The problem ist, that the string itself can contain nodes like (e.g. <image> or something else from my dtd, so i got some problems converting the string to xml. Actually i'm trying this:
     public static void setEditFragment(String content, String xPath) throws Exception {
         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
         DocumentBuilder builder  = factory.newDocumentBuilder();
         Document document = builder.parse("data.xml");
         XPath xpath = XPathFactory.newInstance().newXPath();
         Node node = (Node)xpath.evaluate(xPath, document, XPathConstants.NODE);
         System.out.println(content);
         node.setTextContent(content);
         // Use a XSLT transformer for writing the new XML file
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            // Set output to IsoLatin1
            transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
         DOMSource        source = new DOMSource( document );
         FileOutputStream os     = new FileOutputStream("tmp.xml");
         StreamResult     result = new StreamResult( os );
         transformer.transform( source, result ); 
     }but of course this will not work and sets up some cryptic signs in mein xml document....
can anyone give me advice ?
Thanks !

Well, if you already have the data XML encoded, then just write them to a file:
http://java.sun.com/docs/books/tutorial/essential/io/index.html
Make sure you encode the data with UTF8:
http://java.sun.com/javase/6/docs/api/java/lang/String.html#getBytes(java.lang.String)
Write "<?xml version="1.0" encoding="utf-8"?>" before the data!
Note however, I generally don't recommend to write XML data by hand. Rather use a framework like JAXB.
-Puce
Edited by: Puce on May 8, 2008 1:36 PM

Similar Messages

  • 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.

  • String to XML conversion without fatal error?

    Can one of you tell me how to convert the folowing string to XML without fatal error?
    String s1 = "<?xml version="1.0" encoding="UTF-6.0"?> <Main> <sub> 12345 </sub> </Main>".

    First, you can't have double quotes (") in a string like that, you need to do (\") instead. If you wrote the below line and saved the file as a file_name.xml It should work fine.
    import java.io.*;
    public class yourclass{
         public static void writeXML(){
              try{
                   File xmlOut = new File("file_name.xml");
                   BufferedWriter xmlWriter = new BufferedWriter(new FileWriter(xmlOut));
                   String s1 = "<?xml version=\"1.0\" encoding=\"UTF-6.0\"?> <Main> <sub> 12345 </sub> </Main>";
                   // you can concatenate the strings using a + 
                   // the \n will create a new line in the file
                   String s2 = "<?xml version=\"1.0\" encoding=\"UTF-6.0\"?>" + "\n" +  "<Main> <sub> 12345 </sub> </Main>";
                   xmlWriter.write(s1);
                   xmlWriter.close();
              }catch(Exception ex){
                   ex.printStackTrace();
    }There are a few other ways to do this, the one above is sloppy. One is XStream to convert xml to Java objects and back again. http://xstream.codehaus.org/tutorial.html

  • 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?

  • Coversion of String to XML

    Hi,
    Is there any function or expression in BPEL/XSLT to achieve the conversion of string to xml?
    Just like the function "fn-bea:serialize() "in xquery.
    Thanks in advance,
    Rohini E

    Use :   oraext:parseEscapedXML(contentString)

  • Convertion of String to XML node using Xquery transformation in OSB

    How to convert string to XML node elementusing a built in function using Xquery transformation in OSB?

    check this out - http://www.javamonamour.org/2011/06/fn-beainlinedxml.html
    if in SOA (BPEL & Mediator) you can use oraext:parseXML.
    you should thoroughly analyse where to implement your requirement as some good practices advise to implement more complex logic in SOA and leave OSB to only connect to the services' endpoints.
    Hope this helps,
    A.

  • Conversion of string into XML object

    Hi
    I am having some problems with conversion of string (containing XML data) into Flex XML object and binding it later to UI elements to output/maintain this data.
    Binding of XML structure to UI elements works perfectly fine if I will do following:
    1)      Hardcode XML object within Flex file
    2)      Read xml file from repository (xml file inside the Flex project)
    3)      Use HTTP request to retrieve XML data
    Unfortunately none of the above scenarios suits my solution.
    I am developing a prototype application for processing Flex forms inside SAP system. I have decided to make data bindings using XML structure stored in Data Base. When rendering form inside web browser based application I am retrieving corresponding XML schema (empty for new forms and populated for saved forms) and pass it to Flex form as a string type import parameter. Data is being passed correctly (I can display it on TextArea control for instance) but after conversion to XML and binding to DataGrid I am not getting any results.
    I am converting string (containing XML) to XML object in following way:
    Private var xml_obj:XML = new XML(string_xml );
    I am catching any potential errors but conversion is going well. After conversion I am not getting any results after binding it to DataGrid control and I am not able to access any of the nodes using AS code either. At the same time variable xml_obj is not empty (not null).
    Any help would be much appreciated.
    Regards
    Michael

    David
    First of all sorry for not stating it clearly but I am using Flex 3 for this development (at the moment it is the only choice when embedding Flex objects inside SAP applications).
    You must have missed the bit where I am describing how this XML data finds its way inside Flex. I am passing it to Flex as String type parameter during rendering (directly from DB where it is stored).
    Now, following code works perfect (XML is embedded inside Flex project):
                    <mx:XML id="form_data" source="../assets/example_xml_data.xml"/>
                    <mx:Script>
                                    <![CDATA[
                                                    import mx.collections.XMLListCollection;
                                                    import mx.controls.Alert;
                                                    [Bindable]
                                                    public var XML_list:XMLListCollection;
                                                    private function setParameters():void
                                                                   XML_list = new XMLListCollection(form_data.*);             
                                    ]]>
                    </mx:Script>
                    <mx:DataGrid id="myDataGrid" dataProvider="{XML_list}">
                                    <mx:columns>
                                                    <mx:DataGridColumn dataField="COMMON" headerText="Popular name"/>
                                                    <mx:DataGridColumn dataField="BOTANICAL" headerText="Botanical name"/>
                                                    <mx:DataGridColumn dataField="ZONE" headerText="Zone"/>
                                                    <mx:DataGridColumn dataField="LIGHT" headerText="Light"/>                                                                                                                                               
                                                    <mx:DataGridColumn dataField="PRICE" headerText="Price"/>                                               
                                                    <mx:DataGridColumn dataField="AVAILABILITY" headerText="Availability"/>                                    
                                    </mx:columns>               
                    </mx:DataGrid>
    But following code does not work (XML passed to Flex form as String input parameter):
    import sap.FlashIsland;
    import mx.controls.Alert;
    import mx.collections.XMLListCollection;
    [Bindable]
    public var xml_data:String;
    private var form_data:XML;
    [Bindable]
    private var XML_list:XMLListCollection;
    private function initApp():void
                    FlashIsland.register(this);
    private function setParameters():void
                    try
                                    form_data=new XML(xml_data);
                    catch (error:Error)
                                    Alert.show(error.toString());
                      XML_list = new XMLListCollection(form_data.*);           
    XML string does find its way inside Flex form. I can display content of variable xml_data in TextArea and all looks fine. Conversion to XML (variable form_data) goes well (no error)
    Please helpJ
    Regards
    Michael

  • How to convert xml String to xml file?

    Hi,
    I got a method that do the following:
    public static String convertXmlToString(String xmlFileName) throws Exception
            File file = new File(xmlFileName);
            FileInputStream insr = new FileInputStream(file);
            byte[] fileBuffer = new byte[(int)file.length()];
            insr.read(fileBuffer);
            insr.close();
            return new String(fileBuffer);
         }The return String is the contents of an existing xml file and one example is shown below:
    <object type="server.WOXReference" id="0"><field name="actualPathObj"><object type="java.lang.String" id="1">C:\restClient\actualXMLObjects\812856084.xml</object></field><field name="object"><object type="server.WOXConstructor" id="2"><field name="className"><object type="java.lang.String" id="3">rec.SimpleRecognizer</object></field><field name="types"><array type="java.lang.String" length="3" id="4"><object type="java.lang.String" id="5">double[].class</object><object type="java.lang.String" id="6">double.class</object><object idref="6" /></array></field><field name="args"><array type="java.lang.Object" length="3" id="7"><array type="double" length="5" id="8">22.33 33.22 33.33 22.0 11.0</array><object type="java.lang.Double" id="9">2.2</object><object type="java.lang.Double" id="10">3.3</object></array></field><field name="retType"><object type="java.lang.String" id="11">act</object></field></object></field></object>
    and I want to change the above string to xml file like below:
    <object type="server.WOXReference" id="0"><field name="actualPathObj"><object type="java.lang.String" id="1">C:\restClient\actualXMLObjects\812856084.xml</object></field><field name="object"><object type="server.WOXConstructor" id="2"><field name="className"><object type="java.lang.String" id="3">rec.SimpleRecognizer</object></field><field name="types"><array type="java.lang.String" length="3" id="4"><object type="java.lang.String" id="5">double[].class</object><object type="java.lang.String" id="6">double.class</object><object idref="6" /></array></field><field name="args"><array type="java.lang.Object" length="3" id="7"><array type="double" length="5" id="8">22.33 33.22 33.33 22.0 11.0</array><object type="java.lang.Double" id="9">2.2</object><object type="java.lang.Double" id="10">3.3</object></array></field><field name="retType"><object type="java.lang.String" id="11">act</object></field></object></field></object>How to I change the above xml String back to xml file again? The appropriate tags must be taken care of like > must be > and < must be <.
    Please advice and can give me some sample code.
    Thanks.

    By writing some code that runs through the file and adds a new line for a new element using these methods here...
    http://java.sun.com/j2se/1.4.2/docs/api/org/xml/sax/ContentHandler.html
    i.e.
    startDocument()
    startElement(String namespaceURI, String localName, String qName, Attributes atts)
    endDocument()

  • Converting String To XML Format and send as attachment

    Hi
    My requirement is to convert String into XML Format and that XML File i have to send as an attachment
    can any one one give solution for this Problem.
    Thank you
    Venkatesh.K

    hi,
    i m filling the itab first and converting to xml
    itab contaning these data
    GS_PERSON-CUST_ID   = '3'.
    GS_PERSON-FIRSTNAME = 'Bill'.
    GS_PERSON-LASTNAME  = 'Gates'.
    APPEND GS_PERSON TO GT_PERSON.
    GS_PERSON-CUST_ID   = '4'.
    GS_PERSON-FIRSTNAME = 'Frodo'.
    GS_PERSON-LASTNAME  = 'Baggins'.
    APPEND GS_PERSON TO GT_PERSON.
    after conversion data is coming like that
    #<?xml version="1.0" encoding="utf-16"?>
    <CUSTOMERS>
      <item>
        <customer_id>0003</customer_id>
        <first_name>Bill</first_name>
        <last_name>Gates</last_name>
      </item>
      <item>
        <customer_id>0004</customer_id>
        <first_name>Frodo</first_name>
        <last_name>Baggins</last_name>
      </item>
    </CUSTOMERS>
    but errors are  1) # is coming at the first
                            2)for 'encoding="utf-16"?>', it is not coming perfectly, some other data (iso-8859-1) should come here
    can anybody plz solve it.
    regards,
    viki

  • Converting string to XML format

    Hi All,
    I have a requirement to convert string to xml format and download it. Atpresent, I have a string which is a collection of xml tags. I want to convert this string to xml format like <VALUE004>20387899.437</VALUE004>
    <VALUE005>20387899.437</VALUE005>
    <VALUE006>20387899.437</VALUE006>
    Is there any function module for this.

    Chk this thread.
    Re: Regd: File Conversion to XML format

  • Converting string to xml in xslt

    Hi we are trying to convert string to xml in xslt but it is getting errored out.
    We have followed the procedure mentioned at http://download.oracle.com/docs/cd/A91202_01/901_doc/appdev.901/a88894/adx04xsl.htm under the section "How Do I Convert A String to a Nodeset in XSL?".
    Standard procedure mentioned by oracle is not working. Is it a known bug?

    Chk this thread.
    Re: Regd: File Conversion to XML format

  • How to parse a string containing xml data

    Hi,
    Is it possible to parse a string containing xml data into a array list?
    my string contains xml data as <blood_group>
         <choice id ='1' value='A +ve'/>
         <choice id ='2' value='B +ve'/>
             <choice id ='3' value='O +ve'/>
    </blood_group>how can i get "value" into array list?

    There are lot of Java XML parsing API's available, e.g. JAXP, DOM4J, JXPath, etc.
    Of course you can also write it yourself. Look which methods the String API offers you, e.g. substring and *indexOf.                                                                                                                                                                                                                                                                                                                                                                                                               

  • String to xml object java

    Hello,
    can anyone suggest me how to convert string to xml object in java?
    I have a string (Data) ant now I have to pass it as parameter as xml object, which structure should be:
    <MGWData>Data</MGWData>
    Where I surf I always see only solutions for converting string to xml document, but never to xml object.
    maybe the problem is I don't completely understand what xml object is in first place :/
    Any answer would help.
    Thanks.

    894871 wrote:
    here is the method to call:
    +/**+
    * Sets the p_DATAXMLTYPEIN value for this SVARCHAR2INSERT_RECEIVESInput.
    *+
    * @param p_DATAXMLTYPEIN
    *public void setP_DATAXMLTYPEIN(com.oracle.xmlns.orawsv.SISTEMA_MOKA.MGW_PUBLIC_FUNCTIONS.SVARCHAR2INSERT_RECEIVESInputP_DATAXMLTYPEIN p_DATAXMLTYPEIN) {*
    this.p_DATAXMLTYPEIN = p_DATAXMLTYPEIN;
    one of the classes contains:
    *public class SVARCHAR2INSERT_RECEIVESInputP_DATAXMLTYPEIN  implements java.io.Serializable, org.apache.axis.encoding.AnyContentType {*
    *private org.apache.axis.message.MessageElement [] _any;*
    this method and some classes where generated using eclipse and wsdl file by creating web service client.
    wsdl says for that part: *<xsd:element name="P_DATA-XMLTYPE-IN">*
    So I suppose it should involve smth org.apache.axis.message.MessageElement. But when I create any type of parameter, it gives me error:
    + ....cannot be cast to com.oracle.xmlns.orawsv.SISTEMA_MOKA.MGW_PUBLIC_FUNCTIONS.SVARCHAR2INSERT_RECEIVESInputP_DATAXMLTYPEIN+
    I am new in web service stuff so thank you for response.Can you explain in plain English what you are trying to do? Or provide a [url http://sscce.org/]SSCE.

  • 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.

  • How to display string with XML content in 4.6?

    Hi,
    I`d like to know how to display string with XML content in it for 4.6.
    4.6 has not method parse_string.
    And example like this is not helpful:
      DATA: lo_mxml    TYPE REF TO cl_xml_document.
      CREATE OBJECT lo_mxml.
      CALL METHOD lo_mxml->parse_string
        EXPORTING
          stream = gv_xml_string.
      CALL METHOD lo_mxml->display.
    Thank you.

    Hi,
    May be you can use fm SAP_CONVERT_TO_XML_FORMAT. But it have some issues with memory usage, the program consumed tons of memory during convert.

Maybe you are looking for