Encoding of xml string

Hi,
I am trying to send dynamically built xml string thru xsp page which calls the servlet and sends the xml string as parameter. I can't use URLEncoder because it converts < > to some other chars.
Could some one help or tell me where to find docs for this.
Thanks,

If you have a string that happens to contain XML data, and you want to treat that data as text contents of a containing XML file instead of treating it as markup, then there are two ways to do that. One is to enclose it in a CDATA section:
<![CDATA[...your data goes here...]]>
The other is to escape the XML markup characters: & becomes &amp;, > becomes &gt;, < becomes &lt;, ' becomes &apos;, and " becomes &quot;.
If that wasn't what you meant, try asking a different version of the question.

Similar Messages

  • Getting null value while parsing "XML String" with  encoding WINDOWS-1252.

    Hi,
    when I am converting the Follwoing "xml string " to Document, I am getting the "null" as a document value.
        String strXML =  "<?xml version="1.0" encoding="WINDOWS-1252"?>
                              <category name="SearchByAttributes" value="Search By Attributes">
                                <item name="ORDER_LINE_ID" description="Application Search Attributes" >
                                   <attribute name="Sequence" value="0001"/>
                                 </item>
                                </category>"      
    My "xml string" has the encoding vaule: WINDOWS-1252.
    I am using the following code to convert the "xml string" to Document. I am getting the Document values as a "null" while converting the above "string xml"
            String strXML = //my above string xml.
            DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            docBuilderFactory.setIgnoringElementContentWhitespace(true);
            docBuilder = docBuilderFactory.newDocumentBuilder();
            doc = docBuilder.parse(new InputSource(new StringReader(strXML)));              
            System.out.println("doc value.."+doc)//I am getting null value for "doc".
    Can anyone help me to resolve the issue.

    Thagelapally wrote:
    I am coverting the below "XML string" to Document, once it is converted I am reading that Document,which have an "attribue" Element in.
      String strXML = "<?xml version="1.0" encoding="WINDOWS-1252"?>
    <category name="SearchByAttributes" value="Search By Attributes">
    <item name="ORDER_LINE_ID" description="Application Search Attributes" >
    <attribute name="Sequence" value="0001"/>
    </item>
    </category>" I am using the above code to read the Document. When run the code in "OC4J Server" and using Jdeveloper as an editor,I am able to perfectly read the "attribute" element in the document with out any problem.Println statement printing as I expected.
    System.out.println("Element Name..."+listOfAtt.getNodeName());
    //getting Element Name as...."attribute"(as expected)
    System.out.println("Element Attibrute list....."+elementAtt);
    //getting Element Attribute list as an...."oracle.xml.parser.v2.XMLAttrList@afe"But when run the same code(reading the same Document) in Tomcat and Eclipse,println satatement not printing as i expected.
    System.out.println("Element Name..."+listOfAtt.getNodeName());
    //getting Element Name as...."#text"(I am expecting output value "attribute" but it is printing "#text" which i don't know)
    System.out.println("Element Attibrute list....."+elementAtt);
    //getting Element Attribute list as an...."null"(I am expecting output value object reference but it is printing "null"
    (without the rest of the code, i'm guessing that) most likely you are grabbing the first child node of the item element. however, you are not accounting for some text nodes that are most likely in that list, like the whitespace between the item element and the attribute element. please go read some tutorials on xml, there are thousands of them out there, and they will answer all you initial questions much more efficiently than posting each step to the forums.

  • Exception while unmarshalling UTF-8 encoded XML String, using JAXB.

    hi folks. First of all, thank you for contributing to my queries as of now.
    Problem statement.
    - This happens when i try to unmarshall a webservice response, which is nothing but a simple UTF-8 encoded XML string in an soap envelope.
    - 0xae is the register character: &reg;.
    - My next step was to ensure that my code works without this character. So I removed all occurances from my XML. It worked just fine...
    - So what do you guys suggest me to get rid of this problem?
    - Any suggestion will be treated as valuable resource.
    - Is there some kind of encoding setting with jaxb ?
    An invalid XML character (Unicode: 0xae) was found in the element content of the document.
    org.xml.sax.SAXParseException: An invalid XML character (Unicode: 0xae) was found in the element content of the document.
         at weblogic.apache.xerces.framework.XMLParser.reportError(XMLParser.java:1273)
         at weblogic.apache.xerces.framework.XMLDocumentScanner.reportFatalXMLError(XMLDocumentScanner.java:603)
         at weblogic.apache.xerces.framework.XMLDocumentScanner$ContentDispatcher.dispatch(XMLDocumentScanner.java:1319)
         at weblogic.apache.xerces.framework.XMLDocumentScanner.parseSome(XMLDocumentScanner.java:396)
         at weblogic.apache.xerces.framework.XMLParser.parse(XMLParser.java:1119)
         at weblogic.xml.jaxp.WebLogicXMLReader.parse(WebLogicXMLReader.java:135)
         at weblogic.xml.jaxp.RegistryXMLReader.parse(RegistryXMLReader.java:133)
         at com.sun.xml.bind.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:139)
         at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:129)
         at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:166)
         at com.hp.wwopsit.econfigure.helper.JaxbUtils.xmlStringToJaxbObject(JaxbUtils.java:66)
         at com.hp.wwopsit.econfigure.core.transformation.IPCAdapterMapper.x2oLoadConfig(IPCAdapterMapper.java:376)
         at com.hp.wwopsit.econfigure.core.adapter.IPCAdapter.loadConfiguration(IPCAdapter.java:144)
         at com.hp.wwopsit.econfigure.core.adapter.IPCAdapter.main(IPCAdapter.java:291)
    --------------- linked to ------------------
    javax.xml.bind.UnmarshalException
    - with linked exception:
    [org.xml.sax.SAXParseException: An invalid XML character (Unicode: 0xae) was found in the element content of the document.]
         at javax.xml.bind.helpers.AbstractUnmarshallerImpl.createUnmarshalException(AbstractUnmarshallerImpl.java:284)
         at com.sun.xml.bind.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:143)
         at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:129)
         at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:166)
         at com.hp.wwopsit.econfigure.helper.JaxbUtils.xmlStringToJaxbObject(JaxbUtils.java:66)
         at com.hp.wwopsit.econfigure.core.transformation.IPCAdapterMapper.x2oLoadConfig(IPCAdapterMapper.java:376)
         at com.hp.wwopsit.econfigure.core.adapter.IPCAdapter.loadConfiguration(IPCAdapter.java:144)
         at com.hp.wwopsit.econfigure.core.adapter.IPCAdapter.main(IPCAdapter.java:291)
    ***Jaxb Exception while converting xml file to object. Possible cause, Invalid schema or unrecognized elements in input XML. Actuall exception message:javax.xml.bind.UnmarshalException
    - with linked exception:
    [org.xml.sax.SAXParseException: An invalid XML character (Unicode: 0xae) was found in the element content of the document.]
    End..
    Output completed (44 sec consumed) - Normal Termination

    This is how the XML looks like ..
    <?xml version="1.0" encoding="UTF-8" ?>
    - <configresponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <csticShortText>processor</csticShortText>
    - <csticValues>
    - <csticValue id="024" selected="false">
    <desc>Pentium� 4 1.7GHz/400MHz</desc>
    </configresponse>

  • Extracting elements from an xml string - org.apache.xerces.dom.DeferredText

    Hello all,
    I am new to xml, and I thought I had a handle on things until I got this problem...I am getting an xml string from the body of an e-mail message, and then I am trying to extract elements out of it. Here is an example xml string:
    <?xml version="1.0" encoding="UTF-8"?>
    <filterRoot>
       <filter action="MOVE" bool="AND" name="My Saved Filter" target="Deleted Items">
          <condition attribute="TO" bool="AND" contains="CONTAINS">
             <value>[email protected]</value>
             <value>[email protected]</value>
             <value>[email protected]</value>
             <value>[email protected]</value>
             <value>[email protected]</value>
          </condition>
       </filter>
    </filterRoot>I am trying to extract the <filter> element out and store it into a Vector of Elements (called, not surprisingly, filters). However, I am getting a class cast exception:
    java.lang.ClassCastException: org.apache.xerces.dom.DeferredTextImplIt is being called from where I trying to extract the <filter> in this way:
            filterRoot = doc.getDocumentElement(); // get topmost element
            NodeList list = filterRoot.getChildNodes();
            Vector newFilters = new Vector();
            debug("There are "+list.getLength()+" filters in document");
            for(int i=0; i<list.getLength(); i++) {
                Node n = list.item(i);
                debug("Node "+i+" getNodeValue() is "+n.getNodeValue());
                Element temp = (Element)n;
                newFilters.add(temp);
            }Perhaps my question is, how do I correctly get hold of the <filter> node so that I may cast it as an Element?
    thanks,
    Riz

    Yes, I already knew that it is not a bug.
    But, I got next step problem.
    I put "false" to "include-ignorable-whitespace" feature in xerces parser.
    But, I still found unnecessary TextNodes in my parser object.
    Feature link : http://xerces.apache.org/xerces-j/features.html.
    I use xerces-2_8_0.
    DOMParser parser = new DOMParser();
    parser.setFeature("http://apache.org/xml/features/dom/include-ignorable-whitespace", false);
    parser.parse(inputSource);
    document = ps.getDocument();
    System.out.println(document.getDocumentElement().getChildNodes().length()); // still wrong lengthIs tehre any example of usage this feature?
    What is default defination of white-space "\n "(enter with one space) or " "(juz white space) or something else?
    Thanks,

  • How to get an XML string from a Java Bean without wrting to a file first ?

    I know we can save a Java Bean to an XML file with XMLEncoder and then read it back with XMLDecoder.
    But how can I get an XML string of a Java Bean without writing to a file first ?
    For instance :
    My_Class A_Class = new My_Class("a",1,2,"Z", ...);
    String XML_String_Of_The_Class = an XML representation of A_Class ?
    Of course I can save it to a file with XMLEncoder, and read it in using XMLDecoder, then delete the file, I wonder if it is possible to skip all that and get the XML string directly ?
    Frank

    I think so too, but I am trying to send the object to a servlet as shown below, since I don't know how to send an object to a servlet, I can only turn it into a string and reconstruct it back to an object on the server side after receiving it :
    import java.io.*;
    import java.net.*;
    import java.util.*;
    class Servlet_Message        // Send a message to an HTTP servlet. The protocol is a GET or POST request with a URLEncoded string holding the arguments sent as name=value pairs.
      public static int GET=0;
      public static int POST=1;
      private URL servlet;
      // the URL of the servlet to send messages to
      public Servlet_Message(URL servlet) { this.servlet=servlet; }
      public String sendMessage(Properties args) throws IOException { return sendMessage(args,POST); }
      // Send the request. Return the input stream with the response if the request succeeds.
      // @param args the arguments to send to the servlet
      // @param method GET or POST
      // @exception IOException if error sending request
      // @return the response from the servlet to this message
      public String sendMessage(Properties args,int method) throws IOException
        String Input_Line;
        StringBuffer Result_Buf=new StringBuffer();
        // Set this up any way you want -- POST can be used for all calls, but request headers
        // cannot be set in JDK 1.0.2 so the query string still must be used to pass arguments.
        if (method==GET)
          URL url=new URL(servlet.toExternalForm()+"?"+toEncodedString(args));
          BufferedReader in=new BufferedReader(new InputStreamReader(url.openStream()));
          while ((Input_Line=in.readLine()) != null) Result_Buf.append(Input_Line+"\n");
        else     
          URLConnection conn=servlet.openConnection();
          conn.setDoInput(true);
          conn.setDoOutput(true);           
          conn.setUseCaches(false);
          // Work around a Netscape bug
          conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
          // POST the request data (html form encoded)
          DataOutputStream out=new DataOutputStream(conn.getOutputStream());
          if (args!=null && args.size()>0)
            out.writeBytes(toEncodedString(args));
    //        System.out.println("ServletMessage args: "+args);
    //        System.out.println("ServletMessage toEncString args: "+toEncodedString(args));     
          BufferedReader in=new BufferedReader(new InputStreamReader(conn.getInputStream()));
          while ((Input_Line=in.readLine()) != null) Result_Buf.append(Input_Line+"\n");
          out.flush();
          out.close(); // ESSENTIAL for this to work!          
        return Result_Buf.toString();               // Read the POST response data   
      // Encode the arguments in the property set as a URL-encoded string. Multiple name=value pairs are separated by ampersands.
      // @return the URLEncoded string with name=value pairs
      public String toEncodedString(Properties args)
        StringBuffer sb=new StringBuffer();
        if (args!=null)
          String sep="";
          Enumeration names=args.propertyNames();
          while (names.hasMoreElements())
            String name=(String)names.nextElement();
            try { sb.append(sep+URLEncoder.encode(name,"UTF-8")+"="+URLEncoder.encode(args.getProperty(name),"UTF-8")); }
    //        try { sb.append(sep+URLEncoder.encode(name,"UTF-16")+"="+URLEncoder.encode(args.getProperty(name),"UTF-16")); }
            catch (UnsupportedEncodingException e) { System.out.println(e); }
            sep="&";
        return sb.toString();
    }As shown above the servlet need to encode a string.
    Now my question becomes :
    <1> Is it possible to send an object to a servlet, if so how ? And at the receiving end how to get it back to an object ?
    <2> If it can't be done, how can I be sure to encode the string in the right format to send it over to the servlet ?
    Frank

  • Xml string  to internal table = change  utf-8 to utf-16

    Hello Experts,
    I have a requirement to convert XML String to abap intrnal table .
    I have to get an xml file from application server using opendataset as
    ?<?xml version="1.0" encoding="utf-16" standalone=
    "yes"?><WPUBON01>## <IDOC BEGIN="1">## <EDI_DC
    40 SEGMENT="1">##
    while I am getting as
    <?xml version="1.0" standalone="yes"?>
    <WPUBON01>
    <IDOC BEGIN="1">
    Please advice how I can change the encoding to UTF-16 .
    sun

    Hello Experts,
    I have a requirement to convert XML String to abap intrnal table .
    I have to get an xml file from application server using opendataset as
    ?<?xml version="1.0" encoding="utf-16" standalone=
    "yes"?><WPUBON01>## <IDOC BEGIN="1">## <EDI_DC
    40 SEGMENT="1">##
    while I am getting as
    <?xml version="1.0" standalone="yes"?>
    <WPUBON01>
    <IDOC BEGIN="1">
    Please advice how I can change the encoding to UTF-16 .
    sun

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

  • Parse an XML String

    hi lets say i got an XML String which looks like this..
    String xmlstring = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><GET_REALIZED_GAIN_LOSS_DETAIL_RESPONSE xsi:schemaLocation=\"http://www.statementone.com/webservice/schemas D:\\PMTSchema.xsd\" xmlns=\"http://www.statementone.com/webservice/schemas\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><STATUS>true</STATUS><ERRORS><ERROR><TYPE>String</TYPE><MESSAGE>String</MESSAGE><ERROR_ID>1</ERROR_ID></ERROR><ERROR><TYPE>String</TYPE><MESSAGE>String</MESSAGE><ERROR_ID>1</ERROR_ID></ERROR></ERRORS><GET_REALIZED_GAIN_LOSS_RESULT><XYZ>String</XYZ></GET_REALIZED_GAIN_LOSS_RESULT></GET_REALIZED_GAIN_LOSS_DETAIL_RESPONSE>";
    DocumentBuilderFactory factory =
    DocumentBuilderFactory.newInstance();
    DocumentBuilder db = factory.newDocumentBuilder();
    InputSource inStream = new InputSource();
    inStream.setCharacterStream(new StringReader(xmlstring));
    Document doc1 = db.parse(inStream);
    I notice that all the values i set in XML are available in the doc1 field. But I was not able to get them as a string..
    Can Some one tell me how to get the attributes out of the doc1? I tried getElementBytag and other options.. Do i need to take out the tag items in the sequence in which they are given? or can i select a tag random and pick up the attributes??
    Plzz help me out!!

    Hope this helps you, let me know.
    String xmlstring = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>.......  </GET_REALIZED_GAIN_LOSS_DETAIL_RESPONSE>";
         DocumentBuilderFactory factory =
         DocumentBuilderFactory.newInstance();
         DocumentBuilder db = factory.newDocumentBuilder();
         InputSource inStream = new InputSource();
         inStream.setCharacterStream(new StringReader(xmlstring));
         Document doc1 = db.parse(inStream);
       NamedNodeMap attribes = doc1.getAttributes();
       NodeList nodes = doc1.getChildNodes();http://snippets.dzone.com/posts/show/3575
    http://www.brics.dk/~amoeller/XML/programming/domexample.html
    Message was edited by:
    Srini_Kandula

  • How to create XML string for an object matching the result of a marshal?

    I'm trying to create a XML string representation of an object which exactly matches the XML which results from marshalling the object into a request. I'm almost there except that the XML string I come up with is missing the attribute "standalone=\"yes\"" in the topmost xml element, and this attribute is present in the marshalled XML. I'm using the XML string to create a payload signature which must match exactly with the XML payload of the request, so the two XML representations of the object really do need to be identical.
    Here's what I'm doing to create the XML from the object:
       private String myObjectToXmlString (final MyObject myObject)
           throws Exception {
                 try {
               DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
               Document document = documentBuilder.newDocument();
               myObjectMarshaller.marshal(myObject, document);
               Source source = new DOMSource(document);
               StringWriter stringWriter = new StringWriter();
               Result result = new StreamResult(stringWriter);
               TransformerFactory factory = TransformerFactory.newInstance();
               Transformer transformer = factory.newTransformer();
               transformer.transform(source, result);
               return stringWriter.getBuffer().toString();
           } catch (Exception ex) {
               throw new Exception("Unable to convert a MyObject object to an XML String -- " + ex.toString(), ex);
       }The XML which is produced looks like this:
    <?xml version=\"1.0\" encoding=\"UTF-8\"?>
    <ns2:myObject xmlns:ns2=\"http://sunconnection.sun.com/xml\">
       <myObjectId>0</myObjectId>
       <objectType>1</objectType>
       <description>Test Object</description>
    </ns2:myObject>The payload object is marshalled to the request like so:
        // marshall the MyObject to the output stream
       OutputStream outputStream = myHttpUrlConnection.getOutputStream();
       myObjectMarshaller.marshal(myObject, outputStream);
       outputStream.flush();
       outputStream.close();When I view the XML payload of the request it looks like this:
    <?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>
    <ns2:myObject xmlns:ns2=\"http://sunconnection.sun.com/xml\">
       <myObjectId>0</myObjectId>
       <objectType>1</objectType>
       <description>Test Object</description>
    </ns2:myObject>As you can see the two XML representations of the object are identical except for the standalone attribute in the xml element.
    It'd be a hack to make the assumption that the standalone attribute will always be there in the marshalled object and to just hard code it into the XML string returned by my object to XML method. Since I'm using the same Marshaller to create the XML string as I am to perform the marshalling to the request I assume that there's some way to make it give the same XML in both cases, and that I'm doing something wrong in my method which converts the object to an XML string. If anyone can see where I'm going wrong in that method (myObjectToXmlString() above), or can suggest a better way of doing this, then I'll certainly appreciate the insight.
    --James                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    It turns out that I was taking the wrong approach in my object to XML string method. A cleaner/better way to do it, which gives the correct result, is this:
        private String myObjectToXmlString (final MyObject myObject)
            throws Exception {
            try {
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                myObjectMarshaller.marshal(myObject, stream);
                return stream.toString();
            } catch (Exception ex) {
                throw new Exception("Unable to convert a MyObject object to an XML String -- " + ex.toString(), ex);
        }--James                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Error after transforming xml string

    I have an XML string that I have to parse and update (transformer)
              String ji = "<book><person><first>p</first><last>m</last><age>22</age></person><person><first>b</first><last>g</last><age>46</age></person><person><first>s</first><last>j</last><age>40</age></person></book>";
              ByteArrayInputStream str = new ByteArrayInputStream(ji.getBytes());
                   DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
                   DocumentBuilder docBuilder = documentBuilderFactory.newDocumentBuilder();
                   Document doc = docBuilder.parse(str);
                   doc.getDocumentElement().normalize();
                   str.reset();
                   ByteArrayOutputStream bos = new ByteArrayOutputStream();
                   NodeList listOfPersons = doc.getElementsByTagName("person");
                             int total = listOfPersons.getLength();
                             for(int i = 0; i < total; i++)
                                  Node firstpersonnode = listOfPersons.item(i);
                                  if(firstpersonnode.getNodeType() == Node.ELEMENT_NODE)
                                       Element firstPersonElement = (Element)firstpersonnode;
                                       NodeList firstNameList = firstPersonElement.getElementsByTagName("first");
                                       Element firstNameElement = (Element)firstNameList.item(0);
                                       NodeList textFNList = firstNameElement.getChildNodes();
                                       Text t = (Text) textFNList.item(0);
                                       String p = t.toString();
                                       System.out.println("First Name : " +p);
                                       t.setData("sdasdsa");
                                       //String q = t.toString();
                                       //response.write("First Name : " +q);
                                       NodeList lastNameList = firstPersonElement.getElementsByTagName("last");
                                       Element lastNameElement = (Element)lastNameList.item(0);
                                       NodeList textLNList = lastNameElement.getChildNodes();
                                       System.out.println("Last Name : " + ((Node)textLNList.item(0)).getNodeValue().trim());
                                       NodeList ageList = firstPersonElement.getElementsByTagName("age");
                                       Element ageElement = (Element)ageList.item(0);
                                       NodeList textAgeList = ageElement.getChildNodes();
                                       System.out.println("Age : " + ((Node)textAgeList.item(0)).getNodeValue().trim());
    I then write the ByteArrayOutputStream to an OutputStream becoz I need it in that format for the Transformer.
    oos = bos;
    str.reset();
    Source source = new DOMSource(doc);
    Result res = new StreamResult(oos);
    Transformer x = TransformerFactory.newInstance().newTransformer();
    x.transform(source,res);
    System.out.println("now the string is = "+oos.toString());
    Which Transforms it:
    Now my output is the Old XML string + some xml declaration + the Updated XML string.
    First Name : p
    Last Name : m
    Age : 22
    First Name : b
    Last Name : g
    Age : 46
    First Name : s
    Last Name : j
    Age : 40
    now the string is = <book><person><first>p</first><last>m</last><age>22</age></person><person><first>b</first><last>g</last><age>46</age></person><person><first>s</first><last>j</last><age>40</age></person></book><?xml version="1.0" encoding="utf-8"?>
    <book><person><first>sdasdsa</first><last>m</last><age>22</age></person><person><first>sdasdsa</first><last>g</last><age>46</age></person><person><first>sdasdsa</first><last>j</last><age>40</age></person></book>
    I only need to update the string

    Clap... here is the compilable code complete:
    Tried to make it shorter...:
    public class TestXML {
         public static void main(String[] args) {
              String ji = "<book><person><first>p</first><last>m</last><age>22</age></person><person><first>b</first><last>g</last><age>46</age></person><person><first>s</first><last>j</last><age>40</age></person></book>";
              ByteArrayInputStream str = new ByteArrayInputStream(ji.getBytes());
              ByteArrayOutputStream os=null;
              OutputStream oos = null;
              try
                   DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
                   DocumentBuilder docBuilder =  documentBuilderFactory.newDocumentBuilder();
                   Document doc = docBuilder.parse(str);
                   doc.getDocumentElement().normalize();
                   str.reset();
                   ByteArrayOutputStream bos = new ByteArrayOutputStream();
                   NodeList listOfPersons = doc.getElementsByTagName("person");
                             int total = listOfPersons.getLength();
                             for(int i = 0; i < total; i++)
                                  Node firstpersonnode = listOfPersons.item(i);
                                  if(firstpersonnode.getNodeType() == Node.ELEMENT_NODE)
                                       Element firstPersonElement =  (Element)firstpersonnode;
                                       NodeList firstNameList = firstPersonElement.getElementsByTagName("first");
                                       Element firstNameElement = (Element)firstNameList.item(0);
                                       NodeList textFNList = firstNameElement.getChildNodes();
                                       Text t = (Text) textFNList.item(0);
                                       String p = t.toString();
                                       System.out.println("First Name : " +p);
                                       t.setData("sdasdsa");
                                                                     NodeList lastNameList = firstPersonElement.getElementsByTagName("last");
                                       Element lastNameElement = (Element)lastNameList.item(0);
                                       NodeList textLNList = lastNameElement.getChildNodes();
                                       System.out.println("Last Name : " + ((Node)textLNList.item(0)).getNodeValue().trim());
                                       NodeList ageList = firstPersonElement.getElementsByTagName("age");
                                       Element ageElement = (Element)ageList.item(0);
                                       NodeList textAgeList = ageElement.getChildNodes();
                                       System.out.println("Age : " +   ((Node)textAgeList.item(0)).getNodeValue().trim());
                   byte b;
                   while ((b =(byte) str.read()) != -1) {
                        bos.write(b);
                   oos = bos;
                                            str.reset();
                             Source source = new DOMSource(doc);
                             Result res = new StreamResult(oos);
                             Transformer x =  TransformerFactory.newInstance().newTransformer();
                             x.transform(source,res);
                             System.out.println("now the string is = "+oos.toString());
         catch(Exception e){System.out.println(e);}
    }The o/p is as I mentioned in my first post
    Message was edited by:
    PremPrem
    Message was edited by:
    PremPrem

  • Returning xml string in web service call

    hi all
    i'm writing a server-side web service
    one method i am writing returns a recordset from a db query. i then use jdom to trasnform the recorset to xml and i retrun the xml as a string
    however, my client who is using this web service is having difficulty with the xml string i return - instead of angle brackets it is retruned as &alt &agt
    the client is now able to get rid of the &alt signs but now he cannot traverse through the xml to get the elemnts
    i'm using this code to retrun the xml
    how do others retrun xml within their web sevices?
    try
    RecordsetToXML rsXML = new RecordsetToXML(rs, "ROOT", "UCWSTATS");
    Document jDOMDoc = rsXML.build();
    rs = null;
    XMLOutputter outputter = new XMLOutputter();
    outputter.output(jDOMDoc, writer);
    result = writer.toString();
    writer.close();
    return result;

    Does result end up with a String containing the offending encoded characters, or does it occur when you transfer the xml over the pipe?

  • Printint XML string using  XSLT mapping

    Hi,
    I'm trying to build a outgoing SOAP message with in XI, my backedn legacy application expect the soap message to be in certain format. It expect the xml request passed in the body of the message as whole xml string. I need to pring the xml something like this, I would appreciate if anyone had implemented something like this before. if you look at the below message I'm enclosing the whole xml string in the data element.
    <data xsi:type="xsd:string"><?xml version="1.0" encoding="UTF-8"?> <crm:schedule_call_request session_id="mid://07060623130210031519@elnk_crm.com" target_system_id="csi_ivr" xmlns:crm="https://signup.earthlink.net/ws_xmlc/schema/crm/271005/xmlc_crm.xsd" xmlns:xcommon="https://signup.earthlink.net/ws_xmlc/schema/crm/271005/xmlc_common.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://signup.earthlink.net/ws_xmlc/schema/crm/271005/xmlc_crm.xsd https://signup.earthlink.net/ws_xmlc/schema/crm/271005/xmlc_crm.xsd https://signup.earthlink.net/ws_xmlc/schema/crm/271005/xmlc_common.xsd https://signup.earthlink.net/ws_xmlc/schema/crm/271005/xmlc_common.xsd"> <crm:call_parameter global_rules_version_id="" manual_request="true" originating_skillset="TS (DU/BB)|ADSL RETAIL" parameter_version_id="1" transfer_skillset="TSBBDSL...WinELNK"> <crm:call_id>10031519</crm:call_id> <crm:department_name>TS</crm:department_name> <crm:object_type>CASE</crm:object_type> <crm:object_id>73079085</crm:object_id> <crm:call_time>2007-06-07T12:30:01.000-08:00</crm:call_time> <crm:customer_phone_number>6263452656</crm:customer_phone_number> <crm:override_attempts>false</crm:override_attempts> <crm:retry_count>3</crm:retry_count> <crm:call_trigger>3000</crm:call_trigger> <crm:call_time_padding>10</crm:call_time_padding> <crm:override_local_customer_call_hours>false</crm:override_local_customer_call_hours> </crm:call_parameter> </crm:schedule_call_request></data>

    Hi
    thanks for responding. here is the input SOAP message that I was building in the XLT mapping. I was stuck at putting the xml in the data element.
    soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    - <soapenv:Header>
    - <wsa:EndpointReference soapenv:actor="http://schemas.xmlsoap.org/soap/actor/next" soapenv:mustUnderstand="0" xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing">
      <wsa:Address xsi:type="soapenc:string" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">https://xmlc-qe.corp.earthlink.net/ws_xmlc/s_router</wsa:Address>
      <wsa:ServiceName wsa:PortName="XMLCollectivePort" xsi:type="soapenc:string" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">wsa:ServiceName</wsa:ServiceName>
      </wsa:EndpointReference>
      <wsa:To soapenv:actor="http://schemas.xmlsoap.org/soap/actor/next" soapenv:mustUnderstand="0" xsi:type="soapenc:string" xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">https://xmlc-qe.corp.earthlink.net/ws_xmlc/queues/csi_queue</wsa:To>
      <wsa:Action soapenv:actor="http://schemas.xmlsoap.org/soap/actor/next" soapenv:mustUnderstand="0" xsi:type="soapenc:string" xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">https://xmlc-qe.corp.earthlink.net/ws_xmlc/action//messaging/put_single</wsa:Action>
      <wsa:MessageID soapenv:actor="http://schemas.xmlsoap.org/soap/actor/next" soapenv:mustUnderstand="0" xsi:type="soapenc:string" xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">07060623130210031519</wsa:MessageID>
    - <wsse:Security soapenv:actor="http://schemas.xmlsoap.org/soap/actor/next" soapenv:mustUnderstand="0" xmlns:wsse="http://schemas.xmlsoap.org/ws/2002/07/secext">
    - <wsse:UsernameToken>
      <wsse:Username xsi:type="soapenc:string" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">elnk_crm</wsse:Username>
      <wsse:Password wsse:Type="wsse:PasswordDigest" xsi:type="soapenc:string" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">20UioFa77hI6MLhlc+KPDF95Hx0=</wsse:Password>
      <wsse:Nonce xsi:type="soapenc:string" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">VlX1Jpoq+vkQCQ8af2SaCDP1u9c=</wsse:Nonce>
      <wsu:Created xsi:type="soapenc:string" xmlns:wsu="http://schemas.xmlsoap.org/ws/2002/07/utility" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">2007-06-06T23:13:12Z</wsu:Created>
      </wsse:UsernameToken>
      </wsse:Security>
      </soapenv:Header>
    - <soapenv:Body>
    - <ns1:SubmitRequest soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:ns1="SubmitRequest">
      <data xsi:type="xsd:string"><?xml version="1.0" encoding="UTF-8"?> <crm:schedule_call_request session_id="mid://07060623130210031519@elnk_crm.com" target_system_id="csi_ivr" xmlns:crm="https://signup.earthlink.net/ws_xmlc/schema/crm/271005/xmlc_crm.xsd" xmlns:xcommon="https://signup.earthlink.net/ws_xmlc/schema/crm/271005/xmlc_common.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://signup.earthlink.net/ws_xmlc/schema/crm/271005/xmlc_crm.xsd https://signup.earthlink.net/ws_xmlc/schema/crm/271005/xmlc_crm.xsd https://signup.earthlink.net/ws_xmlc/schema/crm/271005/xmlc_common.xsd https://signup.earthlink.net/ws_xmlc/schema/crm/271005/xmlc_common.xsd"> <crm:call_parameter global_rules_version_id="" manual_request="true" originating_skillset="TS (DU/BB)|ADSL RETAIL" parameter_version_id="1" transfer_skillset="TSBBDSL...WinELNK"> <crm:call_id>10031519</crm:call_id> <crm:department_name>TS</crm:department_name> <crm:object_type>CASE</crm:object_type> <crm:object_id>73079085</crm:object_id> <crm:call_time>2007-06-07T12:30:01.000-08:00</crm:call_time> <crm:customer_phone_number>6263452656</crm:customer_phone_number> <crm:override_attempts>false</crm:override_attempts> <crm:retry_count>3</crm:retry_count> <crm:call_trigger>3000</crm:call_trigger> <crm:call_time_padding>10</crm:call_time_padding> <crm:override_local_customer_call_hours>false</crm:override_local_customer_call_hours> </crm:call_parameter> </crm:schedule_call_request></data>
      </ns1:SubmitRequest>
      </soapenv:Body>
      </soapenv:Envelope>

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

  • Convert XML-String from Codepage utf-16 to ISO-8859-1

    Hi to all experts,
    our system is now unicode with codepage 4102 (UTF-16) and we do an Simple Transformation for creating an XML-String.
    before UniCode : xml_data = <?xml version="1.0" encoding="iso-8859-1"?>#<transactionRequest userID=" .......
    now with UniCode : xml_data = <?xml version="1.0" encoding="utf-16"?>#<transactionRequest userID=".......
    The xml_data transfered to an external Sytem via HTTPS- Communication direct from ABAP.
    The external Sytem send an Error Request:
    <?xml version="1.0" encoding="ISO-8859-1"?>#<transactionResponse>#    <transactionErrorResponse>#        <errorResponse>#            <errorCode>SYS-0001</errorCode>#            <errorDescription>java.lang.Exception: null[ #<?xml version="1.................
    Have you any idea
    Thanks for your help!
    Peter
    Edited by: Peter Pforr on Sep 25, 2008 9:59 AM
    Edited by: Peter Pforr on Sep 25, 2008 10:14 AM

    Darshan,
    Did you get an answer for this question? We have same requirement to create XML file in ISO-8859-1 format with Attributes is set to "Y" and CDATA is being used for data.
    Can you please let me know if you still remember how did you achieve it?
    Satyen...

  • How to get the request xml string in Business service.

    Hi
    I have following requirement
    1) XAI inbound service will get a input xml request feed and call the Business Service.
    2) Business service will do some validation and do the insert in the database.
    My BS schema is as below
    <schema pageAction="change">
    <personId mapField="PER_ID"/>
    <personOrBusiness mapField="PER_OR_BUS_FLG"/>
    <name mapField="ENTITY_NAME" mdField="C1_ENTITY_NAME"/>
    <emailAddress mapField="EMAILID"/>
    <city mapField="CITY"/>
    <county mapField="COUNTY"/>
    <postal mapField="POSTAL"/>
    <houseType mapField="HOUSE_TYPE"/>
    <taxVendorGeographicalCode mapField="GEO_CODE"/>
    <isInCityLimit mapField="IN_CITY_LIMIT"/>
    <state mapField="STATE"/>
    <version mapField="VERSION"/>
    <division mapField="CIS_DIVISION"/>
    <accessGroup mapField="ACCESS_GRP_CD"/>
    <address1 mapField="ADDRESS1"/>
    <personCharacteristic type="list" mapList="CI_PER_CHAR">
    <personId mapField="PER_ID"/>
    <characteristicType mapField="CHAR_TYPE_CD"/>
    <characteristicValue mapField="CHAR_VAL"/>
    <effectiveDate mapField="EFFDT"/>
    <adhocCharacteristicValue mapField="ADHOC_CHAR_VAL"/>
    <characteristicValueForeignKey1 mapField="CHAR_VAL_FK1"/>
    <characteristicValueFK2 mapField="CHAR_VAL_FK2"/>
    <characteristicValueFK3 mapField="CHAR_VAL_FK3"/>
    <characteristicValueFk4 mapField="CHAR_VAL_FK4"/>
    <characteristicValueFK5 mapField="CHAR_VAL_FK5"/>
    </personCharacteristic>
    </schema>
    The request XML to BS is as below_
    (support.schema.AbstractSchemaBasedDispatcher) Performing page:change of BusinessService CM_SPRDSHT_BS' (service='CMSPRDHSHTUPLD'), with input request
    <?xml version="1.0" encoding="UTF-8"?>
    <CM_Person>
    <personOrBusiness>P</personOrBusiness>
    <name>Marsh,Corporate</name>
    <emailAddress>[email protected]</emailAddress>
    <city>Tampa</city>
    <country>USA</country>
    <postal>2131</postal>
    <houseType/>
    <taxVendorGeographicalCode/>
    <isInCityLimit/>
    <state>CA</state>
    <version>1</version>
    <division>930</division>
    <accessGroup>***</accessGroup>
    <address1>Address of Khan</address1>
    </CM_Person>
    I can access the values of each xml node in BS with the help of data item.
    I wanted to know how can I get the above request xml string in my Business Service in Java.

    {color:#0000ff}http://java.sun.com/javase/6/docs/api/java/lang/Integer.html#parseInt(java.lang.String)
    http://java.sun.com/javase/6/docs/api/java/lang/Integer.html#valueOf(java.lang.String){color}

Maybe you are looking for