XML document - request string

Hi Experts,
Could you please tell me, how to pass XML document as a request string to the webservice scenario. Inside the service, I have to do the schema validation for the request . Please guide me, how to proceed further?
Regards
Sara

Hi SARA,
use following Code written in SAX parsing .this will fulfil your requirment.This handle Special character also.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.SAXException;
import com.sap.aii.mapping.api.StreamTransformation;
import com.sap.aii.mapping.api.StreamTransformationException;
public class SimpleForwardMappingString extends DefaultHandler implements StreamTransformation
     private List m_arlCurrent = new ArrayList();
     private List m_arlBOList = new ArrayList();
     private List m_arlObjectList = new ArrayList();
    public static int counter = 0;
     String listName = "newList";
     public  StringBuffer m_totalElementsBuffer = new StringBuffer();
     String startData = "<inCanonStream>";
     String endData = "</inCanonStream>";
     private Map param = null;
     /** Constant Strings used in Forward Mapping */
     public static void main(String args[])
          try {
                  InputStream in = new FileInputStream(new File("C:
Documents and Settings
281152
Desktop
Cannonical12321.xml"));
               OutputStream out = new FileOutputStream(new File("C:
Documents and Settings
281152
Desktop
Cannonical21.xmlOut.xml"));               
               SimpleForwardMappingString myMapping = new SimpleForwardMappingString();
          catch (Exception e)
               e.printStackTrace();
     public void execute(InputStream arg0, OutputStream arg1)
     throws StreamTransformationException
          Writer out;
          try
               out = new OutputStreamWriter(arg1, "UTF16");
               /** Building the SAX parser */
               getXMLDoc(arg0, arg1);
               arg1.write(m_totalElementsBuffer.toString().getBytes("UTF16"));
          catch (IOException e)
               System.out.println("Error : io" + e.getMessage());
          catch (Exception e)
               System.out.println("Error :" + e.getMessage());
     /* (non-Javadoc)
@see com.sap.aii.mapping.api.StreamTransformation#setParameter(java.util.Map)
     public void setParameter(Map arg0)
     public void getXMLDoc(InputStream inputStream, OutputStream outputStream)
Defines a factory API that enables applications to configure and
obtain a SAX based parser to parse XML documents. Once an application
has obtained a reference to a SAXParserFactory it can use the
factory to configure and obtain parser instances.
          SAXParserFactory factory = SAXParserFactory.newInstance();
          try
               factory.setNamespaceAware(true);
               factory.setValidating(true);
               SAXParser saxParser = factory.newSAXParser();
Parse the content of the given {@link java.io.InputStream}
instance as XML using the specified
{@link org.xml.sax.helpers.DefaultHandler}.
@param inputstream InputStream containing the content to be parsed.
@param cobject The SAX DefaultHandler to use.
@exception IOException If any IO errors occur.
@exception IllegalArgumentException If the given InputStream is null.
@exception SAXException If the underlying parser throws a
SAXException while parsing.               
               saxParser.parse(inputStream, this);
          catch (FactoryConfigurationError e)
               System.out.println("Error");
          catch (ParserConfigurationException e)
               e.printStackTrace();
          catch (SAXException e)
               e.printStackTrace();
          catch (IOException e)
               e.printStackTrace();
     /** ===========================================================
                         Methods Overriding in SAX Default Handler
          ===========================================================
Receive notification of the beginning of the document.
By overriding this method in a subclass to take specific actions
at the beginning of a document (such as allocating the root node
of a tree or creating an output file)     
     public void startDocument()throws SAXException
          if(m_totalElementsBuffer.length()>0)
                            m_totalElementsBuffer = new StringBuffer();
                            counter = 0;
          m_totalElementsBuffer.append(m_prologue);
          m_totalElementsBuffer.append(m_nameSpace);
          m_totalElementsBuffer.append(startData);     }
Receive notification of the end of the document.
By overriding this method in a subclass to take specific
actions at the end of a document (such as finalising a tree
or closing an output file)     
     public void endDocument()throws SAXException
          m_totalElementsBuffer.append(endData);
          m_totalElementsBuffer.append(m_rootElementEnd);
Receive notification of the start of an element.
By overriding this method in a subclass to take specific
actions at the start of each element (such as allocating
a new tree node or writing output to a file)
     public void startElement(String namespaceURI, String name, String qName, Attributes attrs)
          throws SAXException
          /** If current List is not empty then append node to StringBuffer */
               m_totalElementsBuffer.append("&lt;" + name + "&gt;");
Receive notification of the end of an element.
By overriding this method in a subclass to take specific
actions at the end of each element (such as finalising
a tree node or writing output to a file)
     public void endElement(String uri, String name, String qName) throws SAXException
               m_totalElementsBuffer.append("&lt;/" + name + "&gt;");
Receive notification of character data inside an element.
By overriding this method to take specific actions for each
chunk of character data (such as adding the data to a node
or buffer, or printing it to a file)     
     public void characters(char buf[], int offset, int len)
          throws SAXException
          String s = new String(buf, offset, len);
          if (null != s && s.length() >0)
               if(s.equalsIgnoreCase("&"))
                     //System.out.println("FOUND AND SYMBOL");
                     String s1 = s.replaceAll("&","_-#_");
                     //System.out.println("s= " +s1);
                     s = s1;
               if(s.equalsIgnoreCase("<"))
                     //System.out.println("FOUND AND SYMBOL");
                     String s1 = s.replaceAll("<","_#-_");
                     //System.out.println("s= " +s1);
                     s = s1;
               m_totalElementsBuffer.append(s);
Thanks
Sunil Singh

Similar Messages

  • Converting XML Document to String

    Dear All,
    I am quite new to Java Web Services. I have made a Java Class which calls all the web services . I am displaying the results on a Command prompt. Below is my sample code:
    import javax.xml.rpc.Service;
    import javax.xml.rpc.Stub;
    import horusWS.Horus_x0020_Web_x0020_Services_Impl;
    import horusWS.Horus_x0020_Web_x0020_ServicesSoap;
    public class JavaClient {
    public static void main(String[] args)
    Horus_x0020_Web_x0020_Services_Impl service = new Horus_x0020_Web_x0020_Services_Impl();
    Horus_x0020_Web_x0020_ServicesSoap port = service.getHorus_x0020_Web_x0020_ServicesSoap();
    String str;
    str = port.getTextFeedbackLearner(1,"P001",1);
    //where getTextFeedbackLearner is the my Web Service.
    System.out.println(str);
    System.out.println returns the web service in string format. Now I want to compare this string to my actual getTextFeedbackLearner.xml file. But I think I need to convert getTextFeedbackLearner.xml to string first. Please let me know
    how can I convert an XML Document to String.
    Thanking you in Anticipation.
    cheers,
    Sunil Sabir

    You can read the XML document as you read any other file.
    Read it into a String variable.
    Check java.io.FileReader, java.io.BufferReader, etc.

  • oms_error Message:[oms] empty or null xml map request string.

    I'm using mapviewer. I create a stored procedure in oracle that uses the utl_http package to make the map request. The omserver response with an error but when i make a map request via internet explorer the server response its ok and show me the correspondent map. This is my pl/sql code it fails in this line:
    UTL_HTTP.SET_HEADER(l_http_req, 'Content-Type', 'application/x-www-form-urlencoded');
         UTL_HTTP.SET_HEADER(l_http_req, 'Content-Lenght', LENGTH(map_request));
         UTL_HTTP.SET_HEADER(l_http_req, 'Host', 'cobogis09');
         UTL_HTTP.SET_HEADER(l_http_req, 'Port', '8888');
    As you can see it tells to me that the map request string is empty but im sending the map request in the next way:
         UTL_HTTP.WRITE_TEXT(l_http_req, '<?xml version="1.0" encoding="UTF-8"?><map_request datasource="stream" srid="8307" basemap="" width="960" height="768" antialiasing="false" format="GIF_URL" title="Demonstration"></map_request>');
         l_http_resp := utl_http.get_response(l_http_req);
         utl_http.read_text(l_http_resp, l_value);
         response := sys.XMLTYPE.createxml(l_value);
         utl_http.end_response(l_http_resp);
         img_url := response.EXTRACT('/map_response/map_image/map_content/@url').getstringval();
    img_url := response.EXTRACT('/map_response/map_image/map_content/@url').getstringval();
    obviously because the server response its not ok
    the server response is (i get this message in my l_value variable):
    <?xml version="1.0" encoding="UTF-8"?><oms_error>Message:[oms] empty or null xml map request string.
    Tue Jul 25 10:37:43 GMT-05:00 2006
    Severity: 0
    Description:
         at oracle.lbs.mapserver.oms.getXMLDocument(oms.java:860)
         at oracle.lbs.mapserver.oms.doPost(oms.java:303)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:760)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at com.evermind.server.http.ServletRequestDispatcher.invoke(ServletRequestDispatcher.java:824)
         at com.evermind.server.http.ServletRequestDispatcher.forwardInternal(ServletRequestDispatcher.java:330)
         at com.evermind.server.http.HttpRequestHandler.processRequest(HttpRequestHandler.java:830)
         at com.evermind.server.http.HttpRequestHandler.run(HttpRequestHandler.java:285)
         at com.evermind.server.http.HttpRequestHandler.run(HttpRequestHandler.java:126)
         at com.evermind.util.ReleasableResourcePooledExecutor$MyWorker.run(ReleasableResourcePooledExecutor.java:192)
         at java.lang.Thread.run(Thread.java:595)
    </oms_error>
    What i want to know its why the server says that the map request string is empty. As you can see the map request is not empty, but when i send to the server something happens that sends this map request string empty to the server.
    The next is the console of the omserver:
    C:\oc4j_extended>cd\
    C:\>cd C:\oc4j_extended\j2ee\home
    C:\oc4j_extended\j2ee\home>java -hotspot -Xmx512M -jar oc4j.jar
    06/07/25 11:00:49 INFO [oracle.lbs.mapserver.oms] oms root path: C:\oc4j_extended\j2ee\home\lbs\mapviewer\web\
    06/07/25 11:00:49 Oracle Application Server Containers for J2EE 10g (10.1.2.0.2) initialized
    06/07/25 11:00:49 INFO [oracle.lbs.mapserver.core.MapperConfig] using default config file: C:\oc4j_extended\j2ee\home\lbs\mapviewer\web\WEB-INF\conf\mapViewerConfig.xml
    06/07/25 11:00:49 WARN [oracle.lbs.mapserver.core.MapperPool] destroying ALL mapmaker instances.
    06/07/25 11:00:50 INFO [oracle.lbs.mapserver.core.MapperConfig] setting logging level to finest
    06/07/25 11:00:50 Tue Jul 25 11:00:50 GMT-05:00 2006 INFO [oracle.sdovis.CacheMgr2] In memory cache limit set to: 512MB
    06/07/25 11:00:50 Tue Jul 25 11:00:50 GMT-05:00 2006 INFO [oracle.lbs.mapserver.core.MapperConfig] Disk-based cache is no longer supported.
    06/07/25 11:00:50 Tue Jul 25 11:00:50 GMT-05:00 2006 INFO [oracle.lbs.mapserver.core.MapperConfig] setting proxy to: coboisa01.ag.ad.local:8080
    06/07/25 11:00:50 Tue Jul 25 11:00:50 GMT-05:00 2006 FINEST [oracle.lbs.mapserver.core.MapperConfig]
    Allowed IPs:
    Excluded IPs:
    06/07/25 11:00:50 Tue Jul 25 11:00:50 GMT-05:00 2006 ERROR [oracle.lbs.mapserver.core.MapperConfig] ###### [MapperConfig] clear-text passwords in the mapViewrConfig.xml file must be prefixed with a '!' (exclamation mark).
    06/07/25 11:00:50 Tue Jul 25 11:00:50 GMT-05:00 2006 INFO [oracle.lbs.mapserver.core.MapperConfig] Map Recycling thread started.
    06/07/25 11:00:50 Tue Jul 25 11:00:50 GMT-05:00 2006 INFO [oracle.lbs.mapserver.oms] *** Oracle MapViewer started. ***
    06/07/25 11:01:03 Tue Jul 25 11:01:03 GMT-05:00 2006 FINEST [oracle.lbs.mapserver.oms] request.getRemoteUser = jazn.com/admin
    06/07/25 11:01:03 Tue Jul 25 11:01:03 GMT-05:00 2006 FINEST [oracle.lbs.mapserver.oms] request= <?xml version="1.0" standalone="yes"?>
    <non_map_request>
    <add_data_source name="stream"
    jdbc_host="cobodata01"
    jdbc_sid="stream"
    jdbc_port="1521"
    jdbc_user="***"
    jdbc_password="***"
    jdbc_mode="thin"
    number_of_mappers="3"/>
    </non_map_request>
    06/07/25 11:01:03 Tue Jul 25 11:01:03 GMT-05:00 2006 FINEST [oracle.lbs.mapserver.oms] getRequestType: nodeName=add_data_source
    06/07/25 11:01:03 Tue Jul 25 11:01:03 GMT-05:00 2006 INFO [oracle.lbs.mapserver.MapServerImpl] adding a map data src [name=stream]
    06/07/25 11:01:05 Tue Jul 25 11:01:05 GMT-05:00 2006 FINEST [oracle.sdovis.SRS] loaded 748 geodetic srids.
    06/07/25 11:01:05 Tue Jul 25 11:01:05 GMT-05:00 2006 INFO [oracle.sdovis.CacheMgr2] Spatial Data Cache opened. Region=SDOVIS_DATA.
    06/07/25 11:01:05 Tue Jul 25 11:01:05 GMT-05:00 2006 INFO [oracle.sdovis.CacheMgr2] max_cache_size=512 MB.
    06/07/25 11:01:05 Tue Jul 25 11:01:05 GMT-05:00 2006 INFO [oracle.sdovis.CacheMgr2] sub region sdovis_subreg_gis_jdbc:oracle:thin:@cobodata01:1521:stream created in cache.
    06/07/25 11:01:05 Tue Jul 25 11:01:05 GMT-05:00 2006 INFO [oracle.lbs.mapserver.core.MapperPool] added a mapper instance to the pool [data src=stream]
    06/07/25 11:01:05 Tue Jul 25 11:01:05 GMT-05:00 2006 INFO [oracle.lbs.mapserver.core.MapperPool] added a mapper instance to the pool [data src=stream]
    06/07/25 11:01:06 Tue Jul 25 11:01:06 GMT-05:00 2006 INFO [oracle.lbs.mapserver.core.MapperPool] added a mapper instance to the pool [data src=stream]
    06/07/25 11:01:36 Tue Jul 25 11:01:36 GMT-05:00 2006 FINEST [oracle.lbs.mapserver.oms] request.getRemoteUser = null
    06/07/25 11:01:36 Tue Jul 25 11:01:36 GMT-05:00 2006 FINEST [oracle.lbs.mapserver.oms] request= null
    As you can see the arrive empty to the server, what can be wrong

    Hi,
    in this map request, it looks that the basemap string is empty.
    UTL_HTTP.WRITE_TEXT(l_http_req, '<?xml version="1.0" encoding="UTF-8"?><map_request datasource="stream" srid="8307" basemap="" width="960" height="768" antialiasing="false" format="GIF_URL" title="Demonstration"></map_request>');

  • XML Document to String - Line Separator problem

    I�m facing a problem with line separator while converting a Document object to String.
    Scenario: I get an input XML having line separator say \n (hex: 0A).
    When I create the output XML using Transformer, the line separator is still \n.
    I have a requirement which makes me convert the transformed Stream into a Document.
    When I try to get the String/bytes from the Document, my line separator is now �\r\n�(hex 0D0A), which is my system�s System property �line-separator�.
    I want to keep the line separator same as that was in input string. So, if the input has the separator has \n, output should have the separator as �\n� and if the input has it as �\r\n�, output should have the same.
    i.e. my hex output should match the hex input.
    Any pointers in the direction are welcome.
    Thanks in advance.

    Can I infer that the parser has changed my document
    line separators when I load it into a Document?
    If yes, is there a way to prevent that from
    happening?I don't really know. Since the XML recommendation says that a parser "MUST" do line-break normalization, I would expect that it does. And I wouldn't design systems that use specific non-XML-approved line endings as a feature, either.

  • String to XML Document

    Can anyone say how to transform a XML String to XML document
    (eg: String xmlstring="<root><main>Title</main></root>";
    How can I transform this to XML Document??
    Guhan

    Right, my mistake, this is what happens when you type code in a browser... hard to compile.
    Document XMLDoc=DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new StringReader("<root><main>Title</main></root&g t;")))PS. Consider following the online JAXP tutorial: http://java.sun.com/xml/tutorial_intro.html

  • Error:SOAP: response message contains an error XIAdapter/PARSING/ADAPTER.SOAP_EXCEPTION - soap fault: Server was unable to read request. --- There is an error in XML document (1, 447). --- Input string was not in a correct format.

    Hi All,
        We have a scenario of FTP-->PI---> Webservice.  While triggering the data in the FTP, it is failing in the PI with the below error
    SOAP: response message contains an error XIAdapter/PARSING/ADAPTER.SOAP_EXCEPTION - soap fault: Server was unable to read request. ---> There is an error in XML document (1, 447). ---> Input string was not in a correct format.
    Can you please help?

    Hi Raja- It seems to be a data quality issue.
    Check for the value @ 1447 position in the xml message that you are trying to send to web service..
    may be a date filed/decimal value which is not in expected format.

  • Parseing an XML Document as a String

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

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

  • Display xml documents - how to submit a feature request?

    Safari is useless when it comes to render raw xml documents. You have to view the actual source to see the xml.
    Is there an official way to submit a feature request for safari to apple? I would love to see something similar to what firefox does with xml. Safari is such a fast and nice browser, if it only could handle text/xml better...

    As you said Safari simply shows all xml element content concatenated together. But no tags or attribute values. If the ContentType in the http header is set to text/xml Firefox shows an xml tree that you can nicely browse. I think IE5+ and Opera do that too. It is important to set the right content type though. Here is an example that shows nice in FF, but is unreadable in Safari:
    http://ww3.bgbm.org/biocase/pywrapper.cgi?dsa=Herbar
    Sure you can look at the source code, but the xml might not be pretty printed.

  • How to create an XML document from a String.

    Can anyone help,
         In the Microsoft XML Document DOM there is a load function load(string) which will create an XML document, but now we are switching to Java and I do not know how to create and XML document from a string, this string �xml document� is passed to my program from a webservice and I need to read several xml elements form it in a web server.
    This string is a well formatted XML document:
    <?xml version="1.0" encoding="UTF-8"?>
    <Countries NumberOfRecords="1" LanguageID="en-us">
         <Country>
              <CountryCode>AU</CountryCode>
              <CountryName>AUSTRALIA</CountryName>
         </Country>
    </Countries>

    Thanks PC!
    I made it work using:
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    factory.setIgnoringComments(true); // We want to ignore comments
    // Now use the factory to create a DOM parser
    DocumentBuilder parser = factory.newDocumentBuilder();
    //TransformThisStringBuffer is a string buffer wich contain the 'XML document (String)'
    InputStream in = new ByteArrayInputStream(TransformThisStringBuffer.toString().getBytes());
    // Parse the InputStream and build the document
    Document document = parser.parse(in);
    But which one is faster InputSource or InputStream, were would you put the "new InputSource(new StringReader(yourString))" in the above code?

  • Converting string to xml Document object.

    Hi all,
    I having a string consiste of xml data.
    I wants to convert this to an xml document object.
    When i am trying to do this i am getting fatal error Premature End of file.
    This is sample code from my program.
    String xmlStr = " <TravelItineraryAddInfoRQ>
    <POS>
    <Source PseudoCityCode="A2PB"/>
    </POS>
    </TravelItineraryAddInfoRQ>";
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware( false );
              DocumentBuilder builder = null;
              char[] ch = new char[1200];
    builder = factory.newDocumentBuilder();
    StringReader sr = new StringReader(xmlStr);
    InputSource is = new InputSource(sr);
    Reader r = is.getCharacterStream();
    r.read(ch);
    System.out.println("String Starting ==== ");
    for(int i=0;i<ch.length;i++)
    System.out.print(ch);
    Document XMLDoc = builder.parse(new InputSource(sr));
    System.out.println("Document Object ==== "+XMLDoc);
    thnx,
    raj

    Hi Rajaven,
    use the below step, I think it could help u
    StringBufferInputStream sb = new StringBufferInputStream(strBf));
    doc = db.parse(sb);first conver a string to StringBufferInputStream then parse to doc Object
    hope it will solve.
    let me know if it's not working
    With cheers,
    PrasannA

  • String representation of the xml document

    hi, I have created the following xml document using the DOM api. I want to the "function" to return a "string" - which represents the xml document i created. How do u do that?
    As of now it doesnt return anything...
    How do u return the entire xml document as character data..? just like
    <root><elements>data</elements></root>....
    anyhelp would be great.
    import java.io.*;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.DocumentBuilder;
    import org.w3c.dom.*;
    public class test1{
    private static void function()throws IOException, DOMException{
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance ();
    DocumentBuilder db = dbf.newDocumentBuilder ();
    Document doc = db.newDocument ();
    Element record = doc.createElement ("record");
    Element name = doc.createElement ("name");
    Element address = doc.createElement ("address");
    Element zip = doc.createElement ("zip");
    Text nameText = doc.createTextNode("bill");
    Text addressText = doc.createTextNode("128, washington");
    Text zipText = doc.createTextNode("10000");
    doc.appendChild(record);
    record.appendChild(name);
    name.appendChild(nameText);
    record.appendChild(address);
    address.appendChild(addressText);
    record.appendChild(zip);
    zip.appendChild(zipText);
    public static void main (String argv [])throws Exception {
    function();
    }

    Brent,
    Looks like you're using the Sun Java Parser. I'll show you how to do it with the Oracle XML Parser and you can extrapolate...
    Document doc = new XMLDocument();
    // Stuff here to build up the DOM Doc
    // with elements, etc.
    // Print the Document to a String
    StringWriter sw = new StringWriter();
    // Wrap the stringwriter in a printwriter
    PrintWriter pw = new PrintWriter(sw);
    // Print to the printwriter
    ((XMLDocument)doc).print(pw);
    // return the string from the stringwriter
    return sw.toString();

  • How to write a string   as an XML Document

    I wrote a web service to receieve a string and then write as an XMl document . But In my writer.java program, I am not doing something right. Please let me know what I am doing wrong.
    Below is writer program:
    public class Writer
    public Writer()
    } public void WriteHabFile(String out, String fileName)
    XMLDocument doc = new XMLDocument();
    try
    XMLPrintDriver output=new XMLPrintDriver(new FileOutputStream(new File(fileName)));
    output.setEncoding("utf-8");
    output.printDocument(doc);
    output.close();
    catch (Exception e)
    System.out.println(e.toString());
    public void WriteLanFile(String out2, String fileName2)
    XMLDocument doc = new XMLDocument();
    try
    XMLPrintDriver output=new XMLPrintDriver(new FileOutputStream(new File(fileName2)));
    output.setEncoding("utf-8");
    output.printDocument(doc);
    output.close();
    catch (Exception e)
    System.out.println(e.toString());
    }

    The problems is that your XML document is not parsed.

  • Parsing String XML Document

    I didn't find a method that parses a XML document when it's not a file. I have a String that I want to parse and the method DocumentBuilder.parse only accepts a String that is a uri to a file.
    I write this code:
    String strXML = "<?xml version='1.0' ?><root><node>anything</node></root>";
    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
    domDoc = docBuilder.parse(strXML);
    Please gimme a light!!
    []'s
    Saulo

    I have a similar problem, I'm trying to do the same BUT in a servlet, it compiles and it actually works if I use it outside my servlet, but, when I mount the servlet with the code similar to this one here it doesn't read the string (at least that's what appears to be, because it doesn't writes to my DB as it should and it doesn't display anything as I'm specifying as my servlet response). Any help? I'm posting my code here:
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.BufferedReader;
    import java.io.FileWriter;
    import java.io.PrintWriter;
    import java.io.File;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.FactoryConfigurationError;
    import javax.xml.parsers.ParserConfigurationException;
    import org.xml.sax.SAXException;
    import org.xml.sax.SAXParseException;
    import org.w3c.dom.*;
    import org.apache.xml.serialize.*;
    import java.net.URLDecoder;
    import java.sql.*;
    import org.xml.sax.InputSource;
    import java.io.StringReader;
    public class SMSConnector extends HttpServlet
    //Public variables we will need
    public String Stringid;
    public String Stringpath;
    public String st;
    public int nid;
    //Servlet service method, which permits listening of events
    public void service(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException
    //Initialization for the servlet
    ServletOutputStream salida = res.getOutputStream();
    ServletInputStream entrada = req.getInputStream();
    //Reading of the entering string
    BufferedReader lector = new BufferedReader(new InputStreamReader (entrada));
    res.setContentType("text/HTML");
    try {
    //Database handler
    Class.forName("org.gjt.mm.mysql.Driver");
    //DocumentBuilderFactory factory =
    //DocumentBuilderFactory.newInstance();
    //DocumentBuilder builder = factory.newDocumentBuilder();
    InputSource inStream = new InputSource();
    inStream.setCharacterStream(new StringReader(lector.readLine()));
    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
    Document doc1 = docBuilder.parse(inStream);
    NodeList listasms = doc1.getElementsByTagName("sms");
    for(int s=0; s<listasms.getLength() ; s++)
    Connection Conn = DriverManager.getConnection ("jdbc:mysql://localhost:3306/smsdb","root", "");
    Node nodosms = listasms.item(s);
    if(nodosms.getNodeType() == Node.ELEMENT_NODE){
    Element elementosms = (Element)nodosms;
    NodeList listatelf = elementosms.getElementsByTagName("tlf");
    Element elementotelf = (Element)listatelf.item(0);
    NodeList textTelfList = elementotelf.getChildNodes();
    String telefono = ((Node)textTelfList.item(0)).getNodeValue();
    //String SendingAddress = ((Node)textAddressList.item(0)).getNodeValue().trim();
    salida.println(telefono);
    NodeList listaop = elementosms.getElementsByTagName("op");
    Element elementoop = (Element)listaop.item(0);
    NodeList textOpList = elementoop.getChildNodes();
    String operadora = ((Node)textOpList.item(0)).getNodeValue();
    NodeList listasc = elementosms.getElementsByTagName("sc");
    Element elementosc = (Element)listasc.item(0);
    NodeList textSCList = elementosc.getChildNodes();
    String shortcode = ((Node)textSCList.item(0)).getNodeValue();
    NodeList listabody = elementosms.getElementsByTagName("body");
    Element elementobody = (Element)listabody.item(0);
    NodeList textBodyList = elementobody.getChildNodes();
    String body = ((Node)textBodyList.item(0)).getNodeValue();
    Statement sta = Conn.createStatement();
    sta.executeUpdate("INSERT INTO smstable (telf,op,sc,body) VALUES ('" + telefono + "','" + operadora + "','" + shortcode + "','" + body + "')");
    Conn.commit();
    Conn.close(); }
    //Catching errors for the SAX and XML parsing
    catch (SAXParseException err)
    System.out.println ("** Parsing error" + ", line " + err.getLineNumber () + ", uri " + err.getSystemId ());
    System.out.println(" " + err.getMessage ());
    catch (SAXException e)
    Exception x = e.getException ();
    ((x == null) ? e : x).printStackTrace ();
    catch (Throwable t)
    t.printStackTrace ();
    }

  • XML document convert into String and Insert into Database

    Hello all,
         In the FIle to File Scenario  I want to send the data to the Reciever System in xml Document and convert into String and insert into Database.
      Please can you tell me exact way how to send it.
    Thanks & Regards,
    Raj

    HI,
    As per my understanding your scenario is File to file where you will get output fiel in XML format.
    Now that XMl payload need to be passed as single string in the database via XI.
    You cauld do this but you need to imply some manipulations such as
    With the help of standard API you need to concatenate the  XML tags and create the structre along with the data.
    For e.g. in your outpuf file the XML structre contain data as
    <field1>ABCD</field1>
    Then in mapping
    The source field will be mappeda s concat(<field1>) + value of  Source field "ABCD" + concat(</field1>) to the target field.
    This is the way that you could achive the requirments else there is no direct way avaialble for it.
    thanks
    Swarup

  • MapViewer API: addMapCacheTheme creates unexpected XML request string

    Hi,
    I try to get a map with map cache theme on it. But MapViewer class generates an xml request string in which an unexpected wfs theme
    exists. So I'm unable to add a map cache theme since the wfs theme causes a problem and i only get an image painted with background
    color...
    my java code is as follows:
                   String viewerUrl = "http://localhost:8888/mapviewer/omserver";
                   String dataSource = "ADATASOURCE";
                   String mapCache= "AMAPCACHE";
                   MapViewer viewer = new MapViewer(viewerUrl);
                   viewer.setDataSourceName(dataSource);
                   viewer.setImageFormat(MapViewer.FORMAT_PNG_URL);
                   viewer.setMapRequestSRID(8307);
                   viewer.setAntiAliasing(false);
                   viewer.setMapTitle(null);
                   viewer.setBackgroundColor(new Color(0xA6CAF0));
                   viewer.setBackgroundImageURL(null);
                   viewer.setDeviceSize(new Dimension(480, 480));
                   //viewer.setBaseMapName(baseMap);
                   viewer.addMapCacheTheme(mapCache, dataSource, mapCache, true);
                   viewer.setCenter(29, 41);
                   viewer.setSize(1);
                   //For debugging issues
                   String req = viewer.getMapRequestString();
                   viewer.run();
    value for req variable is:
    <?xml version="1.0" standalone="yes"?>
    <map_request
    datasource="ADATASOURCE"
    srid="8307"
    width="480"
    height="480"
    bgcolor="#a6caf0"
    antialiase="false"
    format="PNG_URL"
    >
    <center size="1.0">
    <geoFeature>
    <geometricProperty typeName="center">
    <Point>
    <coordinates>29.0,41.0</coordinates>
    </Point>
    </geometricProperty>
    </geoFeature>
    </center>
    <themes>
    <theme name="AMAPCACHE" datasource="ADATASOURCE">
    <map_cache_theme map_cache_name="AMAPCACHE" snap_to_cache_scale="true"/> </theme> <theme name="AMAPCACHE" >
    <wfs_feature_request
    datasource="ADATASOURCE"
    />
    </theme>
    </themes>
    </map_request>
    The first theme is the one that i wanted to add.
    The second one (bold) is the one that causes trouble. I don't know where it comes from.
    This problem occured when i started to use mvclient.jar that came with patch 6453515 which changed MapViewer version from
    Ver10131_B06102 to Ver11_B07100.
    The old mvclient.jar (came with MapViewer Ver10131_B06102) produces the following xml request string:
    <?xml version="1.0" standalone="yes"?>
    <map_request
    datasource="ADATASOURCE"
    srid="8307"
    width="480"
    height="480"
    bgcolor="#a6caf0"
    antialiase="false"
    format="PNG_URL"
    >
    <center size="1.0">
    <geoFeature>
    <geometricProperty typeName="center">
    <Point>
    <coordinates>29.0,41.0</coordinates>
    </Point>
    </geometricProperty>
    </geoFeature>
    </center>
    <themes>
    <theme name="AMAPCACHE" datasource="ADATASOURCE">
    <map_cache_theme map_cache_name="AMAPCACHE" snap_to_cache_scale="true"/> </theme> </themes>
    </map_request>
    What might cause this problem?
    OS: Windows XP Pro SP2
    IDE: JDeveloper 10.1.3.1.0
    Thanks in advance,
    Cihan

    Hi Cihan,
    it is confirmed to be a bug with this client library and it will be fixed. Thanks.
    Joao

Maybe you are looking for

  • How can 2 users collaborate real time on a Pages document?

    I have two computers at home: an iMac and a macbook pro. We have no problem sharing document via the wireless Timecapsule network. Recently, as we have been deep in editing documents using Pages, we were trying to find out how to configure pages so t

  • Soulce gl and target gl in fbl3n report

    Dear Friends, Is it possible to show the source gl and target gl in fbl3n report, can any one solve this. Thanks HK

  • CcBPM Correlation based on filename

    I am new to ccBPM.  The problem I am trying to solve is we have 2 files written; 1 in XML with an element containing the name of the 2nd file and a 2nd file that is a PDF document.  We can get to these files via the File Adapter (NFS).  But we must p

  • MissingResourceException: No localizer class found for message id

    I created a Java Portlet (JSR 168) and am adding it to my portal. For some reason I keep getting the exception below. Any clues why this happens? I added the portlet to the portal file by drag and drop. - vineet No such portlet with URI RSSPortlet_1.

  • Get the node key while using button on toolbar

    HI All I'm using alv tree (class - CL_GUI_ALV_TREE ) and I want to add a button to the toolbar (class - CL_GUI_TOOLBAR ) that User can delete a row from the tree . assume the user put the cursor on row how can i know on which node_key is it ? I am us