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.

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.

  • 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

  • XML Document Not working / Capture device problems HELP!

    Whenever i open the xml file from justin.tv it always says "Log File Cannot Be Created," then ist says "Profile Vlidation"
    And whenever i select my captutre card it always says " Problem With Video Capture Device"
    Somone please help me!
    (i have attached the xml file that keeps on crashing for me)

    You are getting "Log File Cannot Be Created" error because when you download XML file from someone else computer then FMLE  by default folder takes path for Log file as his "My Videos" folder. So while checking the profil, FMLE gets to know that this profile is not perfect and hence gives "Profile Validation Error" and then silently corercts those errors. After clicking OK on "Profile Validation error" window, you can go to Encoding log tab and check the changes that were made in FMLE on above the settings of your XML profile file.
    You are getting "Problem With Video Capture Device" because either the drivers of your device are not corerctly isntalled on your machine or your device is busy with some other application or your device is not connected properly. Please check the drivers and connectivity of your device and make sure that your device gives RAW/Uncompressed Video format only

  • Only one top level element is allowed in an XML document. Line 2, Position 2

    I get this error when I try to run an xsql query with a where clause:
    Only one top level element is allowed in an XML document. Line 2, Position 2
    <font size='-1' face='monospace'>XSQL-005: XSQL page is not well-formed.</font><BR>
    -^
    Here is the xsql query I tried to use.
    <?xml version="1.0"?>
    <xsql:query connection="xmlbook" xmlns:xsql="urn:oracle-xsql">
    select * from companytable where companynumber < 1000;
    </xsql:query>
    null

    You need to escape certain characters in order to make XML documents well formed. The problem in this case is the less than sign between companynumber and 1000. You should replace it with <
    I recommend reading a good XML book - "Building Oracle XML Applications" by Steve Muench, for instance.
    Brian

  • 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

  • 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

  • A space in xml-document is stored in database as New line feed instead of n

    Hello,
    I have got the following problem:
    An xml-document is inserted by an xsql servlet into an object view. First this document is translated by an xsl file. Then an instead of trigger inserts the values into the right tables.
    When a space is present (only one space no further string-value) in the xml-document then this space is inserted into the database as a new line feed.(chr(10))
    When I add the following line to the tag
    <bnr_name xml:space="preserve"> </bnr_name>
    then the space is stored as a space. (chr(32))
    What I want is that this space is inserted as a NULL- value.
    Does anyone know a solution in xml or xsl? (Of course I can solve it on the database side by programming a function around it, but I want to solve it on the xml or xsl side)
    Bye
    jan-Paul Duister

    Few questions which might help to understand the issue.
    1. Is client's data is coming in more than 72 chars per each line? Then you can request client to send the data with max. 72 chars per line. Else dividing the string into 72 chars will loose the readability of text since logic can not be built to divide the text.
    Start reading the text string starting from left for maximum 72 chars . If 72th character is non space then go backwards i.e. read 71, 70, 69... till last character should be a SPACE.
    Eg. string is
    'xxxxxxxxxxx...........This material is created for plant xyz. date of creation is 03.02.2009'.
    x = string72(1) should be a SPACE else take x = string71(1)  and likewise.

  • 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 object access problem?

    Hi,
    I have created a servlet,which will call .sh file, which will call java application.........
    this java application is working as a search engine,which will do search in the XML document object...........This is working fine when only one user run this servlet...........But when more than servlet do the same it is not working......... But once first servlet create the Document object,which is main source for serching..........then second servlet will work fine.......same thing with third servlet and so on...... I used the thread.sleep()/synchronize but it is not working...bcoz i am accessing the same application.....Then instead of servlet i tried to run the java application from the Dos prompt..........But i am facing the same problem......So pl guide me bcoz everything is working excluding this..........Becoz this document object creation is taking some time........ i am creating the object shown below
    Document doc =parseXmlFile("Article.xml", false);
    Element docElem = doc.getDocumentElement();
    public static org.w3c.dom.Document parseXmlFile(String filename, boolean validating)
                   try {
         // Create a builder factory
         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
         factory.setValidating(validating);
         // Create the builder and parse the file
         // org.w3c.dom.Document doc = factory.newDocumentBuilder().parse(filename);
         org.w3c.dom.Document doc = factory.newDocumentBuilder().parse(new File(filename));
         return doc;
    } catch (SAXException e) {
    // A parsing error occurred; the xml input is not valid
    } catch (ParserConfigurationException e) {
    } catch (IOException e) {
    return null;
    }

    Hi,
    This is my Servlet code..............
    package PW.Feed;
    import java.io.*;
    import javax.xml.parsers.*;
    import org.w3c.dom.*;
    import org.xml.sax.*;
    import javax.xml.transform.*;
    import javax.xml.transform.dom.*;
    import javax.xml.transform.stream.StreamResult;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.sql.*;
    import java.util.*;
    public class PrintDom extends HttpServlet
         Document doc;
         Element docElem;
         Connection Conn=null;
         Statement stmt=null,stmt1=null;
         ResultSet rs1=null,rs=null;
         PrintWriter out;
         Vector myVector1=new Vector();
         Vector myVector2=new Vector();
         String strSql="";
         public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException
              res.setContentType("text/html");
              out=res.getWriter();
              try
                   String pubtype=req.getParameter("PubType");
                   String pubDate=req.getParameter("PubDate");
                   String toDate=req.getParameter("ToDate");
                   String fromDate=req.getParameter("FromDate");
                   if(pubDate==null)pubDate="2";
                   if(toDate==null)toDate="02/09/2005";
                   if(fromDate==null)fromDate="02/08/2005";
                   Class.forName("org.firebirdsql.jdbc.FBDriver");
                   Conn = DriverManager.getConnection("jdbc:firebirdsql:192.168.0.15/3050:D:/FBDatabases/PW1.GDB","SYSDBA","cohezia");
                   //Conn = DriverManager.getConnection("jdbc:firebirdsql:192.168.0.99/3050:/share/pw1.gdb","SYSDBA","cohezia");
                   stmt = Conn.createStatement( );
                   if(pubDate.equals("2"))
                        strSql="Select sh.ARTICLEID,sh.cuttingsdate,sh.READDATE,sh.headline,sh.SUMMARY,sh.AUTHOR,sh.PAGEFROM,sh.PUB_NAME,sh.READER_NAME,sh.PARENTTITLE,sh.CANMAIL,sh.PUBLICATION_ID,sh.JOURNALIST_ID,sh.ISPDF FROM SCANSHEADER sh,PUBLICATIONS p where sh.publication_id=p.publication_id and sh.readdate>'"+fromDate+"' and sh.readdate<'"+toDate+"' and p.pubtype='"+ pubtype +"' order by sh.ARTICLEID";
                   else
                        strSql="Select sh.ARTICLEID,sh.cuttingsdate,sh.READDATE,sh.headline,sh.SUMMARY,sh.AUTHOR,sh.PAGEFROM,sh.PUB_NAME,sh.READER_NAME,sh.PARENTTITLE,sh.CANMAIL,sh.PUBLICATION_ID,sh.JOURNALIST_ID,sh.ISPDF FROM SCANSHEADER sh,PUBLICATIONS p where sh.publication_id=p.publication_id and sh.cuttingsdate>'"+fromDate+"' and sh.cuttingsdate<'"+toDate+"' and p.pubtype='"+ pubtype +"' order by sh.ARTICLEID";
                   rs=stmt.executeQuery(strSql);
                   DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
                   doc = builder.newDocument();
                   docElem = doc.createElement("RECORDLIST");
                   doc.appendChild(docElem);
                   Element rootElem = doc.createElement("RECORDS");
                   docElem.appendChild(rootElem);
                   String artid="";
                   while(rs.next())
                             Element artElem = doc.createElement("RECORD");
                             if((rs.getString("ARTICLEID")).length()>0)artElem.setAttribute("id",rs.getString("ARTICLEID"));
                             rootElem.appendChild(artElem);
                             Element rootFieldElem = doc.createElement("FIELDS");
                             artElem.appendChild(rootFieldElem);
                             Element eleCuttingDate = doc.createElement("FIELD");
                             rootFieldElem.appendChild(eleCuttingDate);
                             eleCuttingDate.setAttribute("fieldName","CUTTINGSDATE");
                             if((rs.getString("CUTTINGSDATE")).length()>0) eleCuttingDate.appendChild(doc.createTextNode(rs.getString("CUTTINGSDATE")));
                             Element eleReadDate = doc.createElement("FIELD");
                             rootFieldElem.appendChild(eleReadDate);
                             eleReadDate.setAttribute("fieldName","READDATE");
                             if((rs.getString("READDATE")).length()>0) eleReadDate.appendChild(doc.createTextNode(rs.getString("READDATE")));
                             Element eleHeadLine = doc.createElement("FIELD");
                             rootFieldElem.appendChild(eleHeadLine);
                             eleHeadLine.setAttribute("fieldName","HEADLINE");
                             if((rs.getString("HEADLINE")).length()>0) eleHeadLine.appendChild(doc.createTextNode(rs.getString("HEADLINE")));
                             Element eleSummary = doc.createElement("FIELD");
                             rootFieldElem.appendChild(eleSummary);
                             eleSummary.setAttribute("fieldName","SUMMARY");
                             if(rs.getString("SUMMARY")==null){
                                  //out.println("String is null");
                                  else
                                  {eleSummary.appendChild(doc.createTextNode(rs.getString("SUMMARY")));}
                             Element eleAuthor = doc.createElement("FIELD");
                             rootFieldElem.appendChild(eleAuthor);
                             eleAuthor.setAttribute("fieldName","AUTHOR");
                             if((rs.getString("AUTHOR")).length()>0) eleAuthor.appendChild(doc.createTextNode(rs.getString("AUTHOR")));
                             Element elePageFrom = doc.createElement("FIELD");
                             rootFieldElem.appendChild(elePageFrom);
                             elePageFrom.setAttribute("fieldName","PAGEFROM");
                             if((rs.getString("PAGEFROM")).length()>0) elePageFrom.appendChild(doc.createTextNode(rs.getString("PAGEFROM")));
                             Element elePubName = doc.createElement("FIELD");
                             rootFieldElem.appendChild(elePubName);
                             elePubName.setAttribute("fieldName","PUBNAME");
                             if((rs.getString("PUB_NAME")).length()>0) elePubName.appendChild(doc.createTextNode(rs.getString("PUB_NAME")));
                             Element eleReaderName = doc.createElement("FIELD");
                             rootFieldElem.appendChild(eleReaderName);
                             eleReaderName.setAttribute("fieldName","READER NAME");
                             if((rs.getString("READER_NAME")).length()>0) eleReaderName.appendChild(doc.createTextNode(rs.getString("READER_NAME")));
                             Element eleParentTitle = doc.createElement("FIELD");
                             rootFieldElem.appendChild(eleParentTitle);
                             eleParentTitle.setAttribute("fieldName","PARENTTITLE");
                             if((rs.getString("PARENTTITLE")).length()>0)eleParentTitle.appendChild(doc.createTextNode(rs.getString("PARENTTITLE")));
                             Element eleCanMail = doc.createElement("FIELD");
                             rootFieldElem.appendChild(eleCanMail);
                             eleCanMail.setAttribute("fieldName","CANMAIL");
                             if((rs.getString("CANMAIL")).length()>0) eleCanMail.appendChild(doc.createTextNode(rs.getString("CANMAIL")));
                             Element elePublicationID = doc.createElement("FIELD");
                             rootFieldElem.appendChild(elePublicationID);
                             elePublicationID.setAttribute("fieldName","PUBLICATION_ID");
                             if((rs.getString("PUBLICATION_ID")).length()>0) elePublicationID.appendChild(doc.createTextNode(rs.getString("PUBLICATION_ID")));
                             Element eleJournlistID = doc.createElement("FIELD");
                             rootFieldElem.appendChild(eleJournlistID);
                             eleJournlistID.setAttribute("fieldName","JOURNALIST_ID");
                             if((rs.getString("JOURNALIST_ID")).length()>0) eleJournlistID.appendChild(doc.createTextNode(rs.getString("JOURNALIST_ID")));
                             Element eleIspdf = doc.createElement("FIELD");
                             rootFieldElem.appendChild(eleIspdf);
                             eleIspdf.setAttribute("fieldName","ISPDF");
                             if((rs.getString("ISPDF")).length()>0) eleIspdf.appendChild(doc.createTextNode(rs.getString("ISPDF")));
                             Element rootKeyElem=doc.createElement("KEYWORDS_CODES");
                        String[] arrCodes=getKeyCodes(rs.getString("ARTICLEID"));
                        int count1 = myVector1.size();
                        String[] myArray1=new String[count1];
                        myVector1.copyInto(myArray1);
                        int count2 = myVector2.size();
                        String[] myArray2=new String[count2];
                        myVector2.copyInto(myArray2);
                        for(int j=0;j<arrCodes.length;j++)
                             Element eleKeyword= doc.createElement("KEYWORD_CODE");
                             eleKeyword.setAttribute("CodeId",arrCodes[j]);
                             eleKeyword.setAttribute("LongName",myArray1[j]);
                             eleKeyword.setAttribute("CodeType",myArray2[j]);
                             rootKeyElem.appendChild(eleKeyword);
                        artElem.appendChild(rootKeyElem);
                   Source source = new DOMSource(docElem);
                   //File file = new File("/share/PrintDom.xml");
                   StringWriter rw=new StringWriter();
                   Result result = new StreamResult(rw);
                   //Result result = new DOMResult();
                   // Write the DOM document to the file
                   Transformer xformer = TransformerFactory.newInstance().newTransformer();
                   xformer.transform(source, result);
                   out.println(rw);
              catch (ClassNotFoundException e)
                        out.println("Unable to load Driver Class" + e);
                        return;
                        //fileLog.log(e,"PressWatchFrame1.PressWatchFrame1()");
              catch (SQLException se)
                   out.println(se);
              catch (Exception e)
                   out.println(e);
    finally{
                        try{
                             if(Conn!=null) Conn.close();
                        catch(SQLException ignored){}
         public String[] getKeyCodes(String strArticleId)
              Vector myVector=new Vector();
              myVector1.removeAllElements();
              myVector2.removeAllElements();
         try{
              stmt1=Conn.createStatement( );
              //String strSql1="Select codeid FROM SCANSSUBJECT where articleid='"+ strArticleId +"'";
              String strSql1="Select ss.codeid,c.longname,c.codetype FROM SCANSSUBJECT ss,CODES c where ss.codeid=c.codeid and articleid='"+ strArticleId +"'";
              rs1=stmt1.executeQuery(strSql1);
              String strCodes="";
              while(rs1.next())
                   myVector.add(rs1.getString("codeid"));
                   myVector1.add(rs1.getString("longname"));
                   myVector2.add(rs1.getString("codetype"));
              }catch (SQLException se)
                                       out.println(se);
              int count = myVector.size();
              String[] myArray = new String[count];
              myVector.copyInto(myArray);
              return myArray;
    ..................Thanx

  • Problem with encoding of xml document

    while parsing an xml document with SAX parser, i found that encoding of the xml document received as input stream is "ISO-8859-1" . After parsing certain fields has to be stored in the mysql table where table character set is "utf8" . Now what i found that ceratin characters in the original XML document are stored as question mark (?) in the database.
    1. I am using mysql 4.1.7 with system variable character_set_database as "utf8". So all my tables have charset as "utf8".
    2. I am parsing some xml file as inputsream using SAX parser api (org.apache.xerces.parsers.SAXParser ) with encoding "iso-8859-1". After parsing certain fields have to be stored in mysql database.
    3. Some XML files contain a "iso-8859-1" character with character code 146 which appears like apostrophes but actually it is : - � and the problem is that words like can�t are shown as can?t by database.
    4. I notiicied that parsing is going on well and character code is 146 while parsing. But when i reterive it from the database using jdbc it shows character code as 63.
    5. I am using jdbc to prepared statement to insert parsed xml in the database. It seems that while inserting some problem occurs what is this i don't know.
    6. I tried to convert iso-8859-1 to utf-8 before storing into database, by using
    utfString = new String(isoString.getBytes("ISO-8859-1"),"UTF-8");
    But still when i retreive it from the databse it shows caharcter code as 63.
    7. I also tried to retrieve it using , description = new String(rs.getBytes(1),"UTF-8");
    But it also shows that description contains character with code 63 instead of 146 and it is also showing can�t as can?t
    help me out where is the problem in parsing or while storing and retreiving from database. Sorry for any spelling mistakes if any.

    duggal.ashish wrote:
    3. Some XML files contain a "iso-8859-1" character with character code 146 which appears like apostrophes but actually it is : - &#146; and the problem is that words like can&#146;t are shown as can?t by database.http://en.wikipedia.org/wiki/ISO8859-1
    Scroll down in that page and you'll see that the character code 146 -- which would be 92 in hexadecimal -- is in the "unused" area of ISO8859-1. I don't know where you got the idea that it represents some kind of apostrophe-like character but it doesn't.
    Edit: Actually, I do know where you got that idea. You got it from Windows-1252:
    http://en.wikipedia.org/wiki/Windows-1252
    Not the same charset at all.

  • Problem with XML document created by JDBC Sender adapter

    We are using a sender JDBC adapter to publish data out of a DB2 table.  The message generated by the XI sender adapter seems to have 2 extra characters that break our mapper.  You can see the characters (the dashes on lines 2 and 4) in the XML document that I copied from message monitoring.  Once I remove these dashes and test the mapper in test mode, it works.  If I test with the dashes, the mapper fails. Has anybody else seen this issue?
    Regards,
    Ivailo
      <?xml version="1.0" encoding="utf-8" ?>
    - <ns:CUSTOMER_SCOPE xmlns:ns="http://com.gatx/xi/RCRepairEstimate">
    - <row>
      <CM_CUST_GROUP_CODE>2915</CM_CUST_GROUP_CODE>
      <CM_CUST_SUB_CODE>2</CM_CUST_SUB_CODE>
      <CM_CUST_ID />
      <CM_TERMS>30</CM_TERMS>
      <CM_CUST_SHIPTO_GRP>2915</CM_CUST_SHIPTO_GRP>
      <CM_CUST_SHIPTO_SUB>2</CM_CUST_SHIPTO_SUB>
      <CM_BILL_NAME>GATX RAIL/CANADA</CM_BILL_NAME>
      <CM_BILL_ADDR1>540 5TH AVENUE SW SUITE 1225</CM_BILL_ADDR1>
      <CM_BILL_ADDR2 />
      <CM_BILL_ADDR3 />
      <CM_BILL_CITY>CALGARY ALBERTA</CM_BILL_CITY>
      <CM_BILL_STATE />
      <CM_BILL_ZIP5>0</CM_BILL_ZIP5>
      <CM_BILL_ZIP4>0</CM_BILL_ZIP4>
      <CM_FOREIGN_ZIP>T2P 0M2</CM_FOREIGN_ZIP>
      <CM_ATTENTION>AL FREDERIKSEN</CM_ATTENTION>
      <CM_SALESMAN_INI />
      <CM_DB_RATING />
      <CM_CRED_LIMIT>0</CM_CRED_LIMIT>
      <CM_CRED_FLAG />
      <CM_LAST_CHG_DATE>1282005</CM_LAST_CHG_DATE>
      <CM_CHANGED_BY_USER>XSKISSEL</CM_CHANGED_BY_USER>
      <CM_REORG_CODE>N</CM_REORG_CODE>
      <CM_CORP_GROUP_CODE>0</CM_CORP_GROUP_CODE>
      <CM_CORP_SUB_CODE>0</CM_CORP_SUB_CODE>
      <CM_RECORD_CODE />
      </row>
      </ns:CUSTOMER_SCOPE>

    Hi Ivailo,
    I think the problem lies in the way you copy the data from monitor.
    whenever you want to copy data from XI monitor to test in your IB,make sure you select "view source" and then copy the source message otherwise you will get the browser view of the XML document which contain those "-" for expanding and collapsing the document.
    Regards,
    Sridhar

  • Indices configuration for XML document analysis (indexing time problems)

    Hi all,
    I'm currently developing a tool for XML Document analysis using XQuery. We have a need to analyse the content of a large CMS dump, so I am adding all documents to a berkeley DB xml to be able to run xqueries against it.
    In my last run I've been running to indexing speed problems, with single documents (typically 10-20 K in size) taking around 20 sec to be added to the database after 6000 documents (I've got around 20000 in total). The time needed for adding docs to the database drops with the number of documents.
    I suspect my index configuration to be the reason for this performance drop. Indeed, I've been very generous with indexes, as we have to analyse the data and don't know the structure in advance.
    Currently my index configuration includes:
    - 2 default indicess: edge-element-presence-none and edge-attribute-presence-none to be able to speed up every possible xquery to analyse data patterns: ex. collection()//table//p[contains(.,'help')]
    - 8 edge-attribute-substring-string indices on attributes we use often (id, value, name, ...)
    - 1 edge-element-substring-string index on the root element of the xml documents to be able to speed up document searches: ex. collection()//page[contains(.,'help')]
    So here my questions:
    - Are there any possible performance optimisations in Database config (not index config)? I only set the following:
    setTransactional(false);
    envConf.setCacheSize(1024*64);
    envConf.setCacheMax(1024*256);
    - How can I test various index configuration on the fly? Are there any db tools that allow to set/remove indexes?
    - Is my index config suspect? ;-)
    Greetings,
    Nils

    Hi Nils,
    The edge-element-substring-string index on the document element is almost certainly the cause of the slow document inserts - that's really not a good idea. Substring indexes are used to optimize "=", contains(), starts-with() and ends-with() when they are applied to the named element that has the substring index, so I don't think that index will do what you want it to.
    John

  • Problem validating XMl document

    Hi everyone,
    I'm facing a problem validating a XML document with Apache toolkit under windows XP and eclipse 3.0
    I generate a pair of public/private keys using the RSA algorithm. The keys are of arbitrary length, but satisfying RSA conditions, ie we can encrypt and decrypt.
    I can sign my XML document, but no way to validate it. Validation is only ok when I generate random keys using the KeyPairGenerator.
    Do you think that arbitrary length keys don't allow to validate XML document. And do you have any idea how to solve the problem ( I'm not allowed to generate fixed length keys) ?
    Thansk a lot for your precious help.

    solved!
    urghh...forgot to load th eschema..duh. (must be friday)
    here's the fixed code:
        // parse the xml document (validate the xml string using a schema  file)
        // the xml document does not specified the System ID or location of
        // schema..and use no namespace
        public void parse(HandlerType type, String xmldoc) throws SAXException, IOException {
            File           schema      = schemaMap.get(type);
            DefaultHandler handler     = handlerMap.get(yype);
            XMLReader   reader = XMLReaderFactory.createXMLReader(VENDOR);
            InputSource source = new InputSource(new StringReader(xmldoc));
            reader.setContentHandler(handler);
            reader.setFeature("http://xml.org/sax/features/validation", true);
            reader.setFeature("http://apache.org/xml/features/validation/schema", true);
            reader.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);
            reader.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation",
            "file:///" + schema.getAbsolutePath());
            reader.parse(source);          
        }

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

Maybe you are looking for