Problem parsing an XML

I have this servlet that should be parsing a string received using a HTTP POST, here is the code of the servlet:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.InputSource;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.apache.xml.serialize.*;
import org.xml.sax.InputSource;
public class SMSReceiver extends HttpServlet
public void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
try {
//Initialization for the servlet
ServletInputStream entrada = req.getInputStream();
ServletOutputStream salida = res.getOutputStream();
//Reading of the entering string
BufferedReader lector = new BufferedReader(new InputStreamReader (entrada));
res.setContentType("text/HTML");
try {
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource inStream = new InputSource();
inStream.setCharacterStream(new StringReader(lector.readLine()));
Document doc1 = builder.parse(inStream);
NodeList listasms = doc1.getElementsByTagName("sms");
for(int s=0; s<listasms.getLength() ; s++)
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();
salida.println("Telefono" + 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();
catch (SAXParseException err)
salida.println ("** Parsing error" + ", line " + err.getLineNumber () + ", uri " + err.getSystemId ());
salida.println(" " + err.getMessage ());
catch (SAXException e)
Exception x = e.getException ();
((x == null) ? e : x).printStackTrace ();
catch (Throwable t)
t.printStackTrace ();
The error I get from the servlet is:
** Parsing error, line 1, uri null
XML document structures must start and end within the same entity.
Finished executing
Here's the code of the program that sends the HTTP POST:
import java.io.*;
import java.net.*;
import java.io.*;
public class HTTPSender {
public static void main(String[] args) throws Exception {
try {
String cadena = ""
+ "<root>\n"
+ "<sms>\n"
+ "<tlf>" + (URLEncoder.encode("4123161640" , "UTF-8")) + "</tlf>\n"
+ "<op>" + (URLEncoder.encode("D" , "UTF-8")) + "</op>\n"
+ "<sc>" + (URLEncoder.encode("0000" , "UTF-8")) + "</sc>\n"
+ "<body>" + (URLEncoder.encode("PRUEBA DE MENSAJE MOVIL+" , "UTF-8")) + "</body>\n"
+ "</sms>\n"
+ "</root>";
//URL url = new URL("http://200.74.214.222:8080/MovilPlus/MovilPlusResponse");
URL url = new URL("http://localhost:8080/SMSconnector/SMSReceiver");
int i = 0;
while (i!=1) {
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(cadena);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
System.out.println(line);
wr.close();
rd.close();
i = i + 1;}
} catch (Exception e) {
Now anybody could tell me WHAT I'M DOING WRONG???? Please, need real help here. I'm JAVA newbie but in desperation. Thanks!

Yes, that's the problem kcounsel, thanks for your help, now I'm parsing I modified my code to store the data into a DATABASE, the problem is that it's not storing and neither giving me any exception for the DB, here's the code to see if you can manage something 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;
* This class is made as a servlet for receiving strings and saving
* them as DB records and XML files, it will save each sms in a different XML
* generating the automatic number of the SMS.
* <p>Bugs: (None untill now, please notify if you find one)
* @author (Helder Martins ([email protected]))
public class SMSReceiver 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();
try {
//Reading of the entering string
BufferedReader lector = new BufferedReader(new InputStreamReader (entrada));
res.setContentType("text/HTML");
//Database handler
Class.forName("org.gjt.mm.mysql.Driver");
Connection Conn = DriverManager.getConnection ("jdbc:mysql://localhost:3306/smsdb","root", "");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource inStream = new InputSource(entrada);
Document doc1 = builder.parse(inStream);
NodeList listasms = doc1.getElementsByTagName("sms");
for(int s=0; s<listasms.getLength() ; s++)
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 " + telefono);
NodeList listaop = elementosms.getElementsByTagName("op");
Element elementoop = (Element)listaop.item(0);
NodeList textOpList = elementoop.getChildNodes();
String operadora = ((Node)textOpList.item(0)).getNodeValue();
salida.println("Operadora " + operadora);
NodeList listasc = elementosms.getElementsByTagName("sc");
Element elementosc = (Element)listasc.item(0);
NodeList textSCList = elementosc.getChildNodes();
String shortcode = ((Node)textSCList.item(0)).getNodeValue();
salida.println("Shortcode " + shortcode);
NodeList listabody = elementosms.getElementsByTagName("body");
Element elementobody = (Element)listabody.item(0);
NodeList textBodyList = elementobody.getChildNodes();
String body = ((Node)textBodyList.item(0)).getNodeValue();
salida.println("Body " + body);
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)
salida.println ("** Parsing error" + ", line " + err.getLineNumber () + ", uri " + err.getSystemId ());
salida.println(" " + err.getMessage ());
catch (SAXException e)
Exception x = e.getException ();
((x == null) ? e : x).printStackTrace ();
catch (Throwable t)
t.printStackTrace ();

Similar Messages

  • Problems parsing a XML with binary element

    Hi,
    I'm trying to parse a xml that contains an element with the type "xs:hexBinary".
    The problem is that when i load a file in to the xml everything goes fine ...
    no matter the size of the file (i've tested it with 6Mb file), the problem is
    that when i try to parse it i got an error "java.lang.OutOfMemoryError" ... i
    don't know if there is any kind of size restriction or something like that.
    Any information would be gratefully considered.
    Thanks a lot.
    Rober.

    XML is a text format so of course it can't include binary data such as GIFs. But then so is HTML, so there doesn't seem to be much point in doing this. Your HTML would have to include a link to the GIF, rather than the GIF itself in any format, binary or otherwise. And therefore so should the XML. Given all that, it follows that parsers don't deal with whatever it is you are attempting.

  • Problem parsing a xml using Jdom

    Hi all,
    I am reposting it as I was told to format the code and send it again.
    I am trying to parse a xml file using a jdom java code.This code works fine if I remove xmlns attribute in the root element. (I get the expected result) .If the "xmlns" attribute is put in the xml as it should be then the parsing and retrieving returns null. Please tell me how to fix this issue.
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Xml
    <process name="CreateKBEntryService" targetNamespace="http://serena.com/CreateKBEntryService" suppressJoinFailure="yes" xmlns:tns="http://serena.com/CreateKBEntryService" xmlns="http://schemas.xmlsoap.org/ws/2003/03/business-process/" xmlns:bpelx="http://schemas.oracle.com/bpel/extension" xmlns:ora="http://schemas.oracle.com/xpath/extension" xmlns:nsxml0="http://localhost:8080/axis/services/CreateKBEntryService" xmlns:nsxml1="http://DefaultNamespace" xmlns:bpws="http://schemas.xmlsoap.org/ws/2003/03/business-process/">
    <partnerLinks>
    <partnerLink name="client" partnerLinkType="tns:CreateKBEntryService" myRole="CreateKBEntryServiceProvider"/>
    <partnerLink name="CreateKBEntryPartnerLink" partnerLinkType="nsxml0:CreateKBEntryLink" partnerRole="CreateKBEntryProvider"/>
    </partnerLinks>
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~`
    Java:
    import java.io.*;
    import java.util.*;
    import org.jdom.Document;
    import org.jdom.Element;
    import org.jdom.input.SAXBuilder;
    public class sample1 {
    public static void main(String[] args) throws Exception {
    // create a XML parser and read the XML file
    SAXBuilder oBuilder = new SAXBuilder();
    Document oDoc = oBuilder.build(new File("**xml file location**"));
    Element root = oDoc.getRootElement();
    System.out.println(root.getName());
    String tgtns= root.getAttributeValue("targetNamespace");
    System.out.println("tgt ns "+ tgtns);
    List list= root.getChildren("partnerLinks");
    Iterator it1= list.iterator();
    System.out.println("Iterator 1 - "+list.size());
    while(it1.hasNext()){
    Element partnerlinks = (Element)it1.next();
    List list2= partnerlinks.getChildren("partnerLink");
    System.out.println("iterator 2 - "+list2.size());
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Result:
    Without Xmlns in xml file(Expected and correct output)
    process
    tgt ns http://serena.com/CreateKBEntryService
    Iterator 1 - 1//expected and correct result that comes when I remove xmlns attribute from xml
    iterator 2 - 2
    Result with xmlns:
    process
    tgt ns http://serena.com/CreateKBEntryService
    Iterator 1 - 0 //instead of 0 should return 1

    One suggestion to try:
    Change your code to the following
    Element root = oDoc.getRootElement();
    System.out.println(root.getName());
    String tgtns= root.getAttributeValue("targetNamespace");
    System.out.println("tgt ns "+ tgtns);
    Namespace ns = Namespace.getNamespace(
      "http://schemas.xmlsoap.org/ws/2003/03/business-process/" );
    List list= root.getChildren("partnerLinks", ns );
    Iterator it1= list.iterator();
    System.out.println("Iterator 1 - "+list.size());The JavaDoc says for the one-arg getChildren()
    If this target element has no nested elements with the given name outside a namespace, an empty List is returned.
    Your elements have a namespace (the default one) so it should be worth a try.
    Dave Patterson

  • Can someone help me with a problem of parsing an XML file?

    Hello,
    I'm having some problems parsing an xml file. I get a SAXNotSupportedException when setting a property value.
    Here is the piece of code where I have the problem:
    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setNamespaceAware(true);
    SAXParser saxParser = spf.newSAXParser();
    XMLReader xmlReader = saxParser.getXMLReader();
    DefaultHandler defHandler = new DefaultHandler();
    xmlReader.setProperty("http://xml.org/sax/properties/lexical-handler", defHandler);
    and the log is:
    Problem with the parser org.xml.sax.SAXNotSupportedException: PAR012 For propertyID "http://xml.org/sax/properties/lexical-handler", the value "org.xml.sax.helpers.DefaultHandler@4ff4f74a" cannot be cast to LexicalHandler.
    http://xml.org/sax/properties/lexical-handler org.xml.sax.helpers.DefaultHandler@4ff4f74a LexicalHandler
    I've been working on this problem but I can't find the error.
    Does anyone have an idea of what to do to solve it?
    Thanx in advance,
    M@G

    before deciding which XML technology to use, you should see if your application fit in the category below:
    use SAX:
    1. The XML file is rather large (30 or 40+ MB)
    2. I don't need the xml document in memory. I will parse the document and store the data in my own object.
    use DOM or JDOM
    1. The XML file is relatively small (less than 30 MB) or I can increase the runtime memory for larger xml file.
    2. I will need to walk up and down the xml document tree severals time.
    3. My application is in Java and it's not going to be rewritten in C++, etc (use JDOM)
    NOTE:
    JDOM is rather easier to use (for Java developer), but it's not an www.org.com standardlized xml parser.
    personally, i like JDOM for traversing the DOM.

  • How do I parse a XML document?

    Hello
    I have a problem parsing a XML-document like the one below: Can anyone help me with a code example or something to get the tag "<Name>" out so that I get the string "Example5" and "Example3" out.
    Thnx for any help!
    Jimmy
    The XML file looks like this (but without the line in the beginning of each row):
    <?xml version="1.0" encoding="UTF-8"?>
    <!-- edited with XML Spy v4.4 U (http://www.xmlspy.com) -->
    <!DOCTYPE ThisExample SYSTEM "C:/example.dtd">
    <?xml-stylesheet type="text/xsl" href="first.xslt"?>
    <ThisExample>
    ____<Product>
    ________<Product_number>no1</Product_number>
    ________<Number>number1</Number>
    ____</Product>
    ____<Product>
    ________<Product_number>no2</Product_number>
    ________<Number>number2</Number>
    ____</Product>
    ____<Group>
    ________<Type>EX1</Type>
    ________<ProductVersionAllowed>Y</ProductVersionAllowed>
    ________<Preprocess>precmd.csh</Preprocess>
    ________<Postprocess>echo Finished</Postprocess>
    ________<Document>
    ____________<Name>Example1</Name>
    ____________<Product_number>no1</Product_number>
    ____________<Ticked_by_default>Y</Ticked_by_default>
    ________</Document>
    ________<Document>
    ____________<Name>Example2</Name>
    ____________<Product_number>no1</Product_number>
    ____________<Ticked_by_default>Y</Ticked_by_default>
    ________</Document>
    ________<Document>
    ____________<Name>Example3</Name>
    ____________<Product_number>no1</Product_number>
    ____________<Ticked_by_default>Y</Ticked_by_default>
    ________</Document>
    ____</Group>
    ____<Group>
    ________<Type>EX2</Type>
    ________<ProductVersionAllowed>N</ProductVersionAllowed>
    ________<Preprocess>precmd.csh</Preprocess>
    ________<Postprocess>echo Finished</Postprocess>
    ________<Document>
    ____________<Name>Example4</Name>
    ____________<Product_number>no2</Product_number>
    ____________<Ticked_by_default>Y</Ticked_by_default>
    ________</Document>
    ________<Document>
    ____________<Name>Example5</Name>
    ____________<Product_number>no2</Product_number>
    ____________<Ticked_by_default>Y</Ticked_by_default>
    ________</Document>
    ____</Group>
    </ThisExample>

    Thnx :O)
    Now it worx!
    Just one more thing. Can I get the number of elements there is in a tag? I.e. how many "Document"'s there are in 1 "Group"? I need this because I have too loop through a "Group" and print the name of every "Document".
    At the moment I'm doing it like below, but that is not a nice solution, and it realy does not work that well:
    Jimmy
    int i = 1;
    do
    node = org.apache.xpath.XPathAPI.selectSingleNode(doc, "/PosttoolControl/Group[position()=" + i + "]/Type");
    if (node.getFirstChild().getNodeValue() != null)
    type = node.getFirstChild().getNodeValue();
    PostToolDocGroupeComboBox.addItem(type);
    i++;
    } while (node.getFirstChild().getNodeValue() != null);

  • Problem in parsing an XML using SAX parser

    Hai All,
    I have got a problem in parsing an XML using SAX parser.
    I have an XML (sample below) which need to be parsed
    <line-items>
    <item num="1">
         <part-number>PN1234</part-number>
         <quantity uom="ea">10</quantity>
         <lpn>LPN1060</lpn>
         <reference num="1">Line ref 1</reference>
         <reference num="2">Line ref 2</reference>
         <reference num="3">Line ref 3</reference>
    </item>
    <item num="2">
         <part-number>PN1527</part-number>
         <quantity uom="lbs">5</quantity>
         <lpn>LPN2152</lpn>
         <reference num="1">Line ref 1</reference>
         <reference num="2">Line ref 2</reference>
         <reference num="3">Line ref 3</reference>
    </item>
    <item num="n">
    </item>
    </line-items>
    There can be any number of items( 1 to n). I need to parse these
    item values using SAX parser and invoke a stored procedure for
    each item with its
    values(partnumber,qty,lpn,refnum1,refnum2,refnum3).
    Suppose if there are 100 items, i need to invoke the stored
    procedure sp1() 100 times for each item.
    I need to invoke the stored procedure in endDocument() method of
    SAX event handler and not in endelement() method.
    What is the best way to store those values and invoke the stored
    procedure in enddocument() method.
    Any help would br greatly appreciated.
    Thanks in advance
    Pooja.

    VO or ValueObject is a trendy new name for Beans.
    So just create an item class with variables for each of the sub elements.
    <item>
    <part-number>PN1234</part-number>
    <quantity uom="ea">10</quantity>
    <lpn>LPN1060</lpn>
    <reference num="1">Line ref 1</reference>
    <reference num="2">Line ref 2</reference>
    <reference num="3">Line ref 3</reference>
    </item>
    public class ItemVO
    String partNumber;
    int quantity;
    String quantityType;
    String lpn;
    List references = new ArrayList();
    * @return Returns the lpn.
    public String getLpn()
    return this.lpn;
    * @param lpn The lpn to set.
    public void setLpn(String lpn)
    this.lpn = lpn;
    * @return Returns the partNumber.
    public String getPartNumber()
    return this.partNumber;
    * @param partNumber The partNumber to set.
    public void setPartNumber(String partNumber)
    this.partNumber = partNumber;
    * @return Returns the quantity.
    public int getQuantity()
    return this.quantity;
    * @param quantity The quantity to set.
    public void setQuantity(int quantity)
    this.quantity = quantity;
    * @return Returns the quantityType.
    public String getQuantityType()
    return this.quantityType;
    * @param quantityType The quantityType to set.
    public void setQuantityType(String quantityType)
    this.quantityType = quantityType;
    * @return Returns the references.
    public List getReferences()
    return this.references;
    * @param references The references to set.
    public void setReferences(List references)
    this.references = references;

  • XML parsing problems with Oracle XML parser for PL/SQL

    I am using the Oracle XML parser for PL/SQL to transform XML into HTML usign XSL. The parser gives me sporadic errors trying to parse various XML documents. For the same XML source, the XMLPARSER will parse without errors one day and the next day will give me errors such as "invalid char in text", "Expected ';'.", or even Java null pointer exceptions.
    I have verified that the XML sources are well formed, so I am pretty certain that the problems I am having are bugs in the XMLPARSER.
    Is there going to be a XML parser for PL/SQL version 2 that will fix these bugs? If so, when??? If not, is there anything else I could do to fix these problems?
    Thanks!

    You can use the latest version.

  • JSTL - Problem parsing XML file w/ XML schema declarations

    I'm having trouble parsing an xml document that contains XML schema declarations in the root element. I've included 2 snippets, the XML files they're supposed to parse, and their output below. The first one works and the second one doesn't. Could someone please tell me why? I find it hard to believe that no one's run into this before.
    I'm running Tomcat 5.5 and I'm using JSP 2.0, jakarta standard taglibs jars (1.1.2), jdk 1.5.0_04, and the Xalan 2.7.0 jars.
    Here's the first snippet:
    <c:import url="/WEB-INF/config/schools.xml" var="xml" />
    <x:parse doc="${xml}" var="schoolList"/>
    There are <x:out select="count($schoolList//school)"/> schools in the file:<br/>
    <x:forEach select="$schoolList//school">
         <x:out select="name"/><br/>
    </x:forEach>it parses the following xml file:
    <?xml version="1.0" encoding="UTF-8"?>
    <schools>
         <school id="34033">
              <name>Tumwater Middle School</name>
              <district>Tumwater</district>
              <type>middle</type>
              <active>false</active>
         </school>
         <school id="17001">
              <name>Garfield High School</name>
              <district>Seattle</district>
              <type>high</type>
              <active>true</active>
         </school>
         <school id="00023">
              <name>Tigard High School</name>
              <district>Tigard-Tualatin</district>
              <type>high</type>
              <active>true</active>
         </school>
    </schools>and it outputs:
    There are 3 schools in the file:
    Tumwater Middle School
    Garfield High School
    Tigard High School-----------------------------------------
    The second snippet:
    <c:import url="/WEB-INF/config/schools2.xml" var="xml2" />
    <x:parse doc="${xml2}" var="schoolList2"/>
    There are <x:out select="count($schoolList2//school)"/> schools in the file:<br/>
    <x:forEach select="$schoolList2//school">
         <x:out select="name"/><br/>
    </x:forEach>parses this xml file (note the xml schema declarations):
    <?xml version="1.0" encoding="UTF-8"?>
    <schools xmlns="http://www.serenus.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.serenus.com schools.xsd">
         <school id="34033">
              <name>Tumwater Middle School</name>
              <district>Tumwater</district>
              <type>middle</type>
              <active>false</active>
         </school>
         <school id="17001">
              <name>Garfield High School</name>
              <district>Seattle</district>
              <type>high</type>
              <active>true</active>
         </school>
         <school id="00023">
              <name>Tigard High School</name>
              <district>Tigard-Tualatin</district>
              <type>high</type>
              <active>true</active>
         </school>
    </schools>and its output is:
    There are 0 schools in the file:That's it! No errors at all! I'm 100% certain the variable names, filenames, etc. are correct. I've looked everywhere for an existing answer to this problem, but I can't find one. Is this a known issue? Please help.
    -Ben

    Hi Ben,
    I got exactly the same problem and also could not find any solution.
    Did you find a way out for this problem meanwhile?
    Any help is welcome!

  • Problem parsing xml(J2ME Web Service spec) containing image in cldc/midp

    Hi,
    I have created a restful web service that generates xml file in app server. I have created xml file using JAXB2.1 spec. This xml file has many elements starting from char data to image (binary data). I could successfully create xml file and developed another test client to read the same file using JAXB. However, I am finding a problem while getting the image in the java me client (cldc1.1 and midp2.0).
    I am using J2ME Web Services Specification, using javax.xml.parsers.SAXParser to parse the xml file. Parsing is successful and got the character data. But the image data is not accurate, so I am not getting the image. I suspect the problem is with encoding but not sure how to solve this. At the server end, I verified that xml file is encoded with "UTF-8" encoding, not sure how to decode at the client end.
    I am totally confused as how to get the accurate image data, not sure if I use kxml parser would solve my problem.
    I would really appreciate if somebody can get back to me as this is very very important.

    Try to send to your web service the byte array instead of string and then convert the byte array into an image
    using a method like the following one in your service:
    // C# code
    public Image ByteArrayToImage(byte[] byteArrayIn)
         MemoryStream ms = new MemoryStream(byteArrayIn);
         Image returnImage = Image.FromStream(ms);
         return returnImage;
    }There can be some problem between encoding in J2ME and .Net so try different encodings in gathering the image bytes in your j2ME application, but, instead of jpg which has more encodings, try png that is a more standardized image compression(open standard).

  • Problem parsing configuration/hibernate.cfg.xml

    I am trying to integrate struts with hibernate. I have created a plug-in for that and copied all the necessary jars & xmls to the classpath. I am providing the full stack trace, can any one say what could be the problem
    net.sf.hibernate.HibernateException: problem parsing configuration/hibernate.cfg
    .xml
    at net.sf.hibernate.cfg.Configuration.doConfigure(Configuration.java:963
    at net.sf.hibernate.cfg.Configuration.configure(Configuration.java:902)
    at net.sf.hibernate.cfg.Configuration.configure(Configuration.java:888)
    at com.plugin.HibernatePlugIn.initHibernate(HibernatePlugIn.java:72)
    at com.plugin.HibernatePlugIn.init(HibernatePlugIn.java:54)
    at org.apache.struts.action.ActionServlet.initModulePlugIns(ActionServle
    t.java:869)
    at org.apache.struts.action.ActionServlet.init(ActionServlet.java:336)
    at javax.servlet.GenericServlet.init(GenericServlet.java:211)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.
    java:1029)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:86
    2)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContex
    t.java:4013)
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:4
    357)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase
    .java:823)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:80
    7)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:595)
    at org.apache.catalina.core.StandardHostDeployer.install(StandardHostDep
    loyer.java:277)
    at org.apache.catalina.core.StandardHost.install(StandardHost.java:832)
    at org.apache.catalina.startup.HostConfig.deployWARs(HostConfig.java:625
    at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:431
    at org.apache.catalina.startup.HostConfig.start(HostConfig.java:983)
    at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java
    :349)
    at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(Lifecycl
    eSupport.java:119)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1091)
    at org.apache.catalina.core.StandardHost.start(StandardHost.java:789)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1083)
    at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:478
    at org.apache.catalina.core.StandardService.start(StandardService.java:4
    80)
    at org.apache.catalina.core.StandardServer.start(StandardServer.java:231
    3)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:556)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.
    java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAcces
    sorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:324)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:287)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:425)
    Caused by: org.dom4j.DocumentException: hibernate.sourceforge.net Nested excepti
    on: hibernate.sourceforge.net
    at org.dom4j.io.SAXReader.read(SAXReader.java:358)
    at net.sf.hibernate.cfg.Configuration.doConfigure(Configuration.java:958
    )

    Looks like a problem with Hibernate itself parsing the config file?
    Here's a posting from the Hibernate forum that sounds similar:
    http://forums.hibernate.org/viewtopic.php?p=2256871&highlight=&sid=e1090f717891db4535310102c61bec25
    -steve-

  • Problem parsing XML with schema when extracted from a jar file

    I am having a problem parsing XML with a schema, both of which are extracted from a jar file. I am using using ZipFile to get InputStream objects for the appropriate ZipEntry objects in the jar file. My XML is encrypted so I decrypt it to a temporary file. I am then attempting to parse the temporary file with the schema using DocumentBuilder.parse.
    I get the following exception:
    org.xml.sax.SAXParseException: cvc-elt.1: Cannot find the declaration of element '<root element name>'
    This was all working OK before I jarred everything (i.e. when I was using standalone files, rather than InputStreams retrieved from a jar).
    I have output the retrieved XML to a file and compared it with my original source and they are identical.
    I am baffled because the nature of the exception suggests that the schema has been read and parsed correctly but the XML file is not parsing against the schema.
    Any suggestions?
    The code is as follows:
      public void open(File input) throws IOException, CSLXMLException {
        InputStream schema = ZipFileHandler.getResourceAsStream("<jar file name>", "<schema resource name>");
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = null;
        try {
          factory.setNamespaceAware(true);
          factory.setValidating(true);
          factory.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
          factory.setAttribute(JAXP_SCHEMA_SOURCE, schema);
          builder = factory.newDocumentBuilder();
          builder.setErrorHandler(new CSLXMLParseHandler());
        } catch (Exception builderException) {
          throw new CSLXMLException("Error setting up SAX: " + builderException.toString());
        Document document = null;
        try {
          document = builder.parse(input);
        } catch (SAXException parseException) {
          throw new CSLXMLException(parseException.toString());
        }

    I was originally using getSystemResource, which worked fine until I jarred the application. The problem appears to be that resources returned from a jar file cannot be used in the same way as resources returned directly from the file system. You have to use the ZipFile class (or its JarFile subclass) to locate the ZipEntry in the jar file and then use ZipFile.getInputStream(ZipEntry) to convert this to an InputStream. I have seen example code where an InputStream is used for the JAXP_SCHEMA_SOURCE attribute but, for some reason, this did not work with the InputStream returned by ZipFile.getInputStream. Like you, I have also seen examples that use a URL but they appear to be URL's that point to a file not URL's that point to an entry in a jar file.
    Maybe there is another way around this but writing to a file works and I set use File.deleteOnExit() to ensure things are tidied afterwards.

  • StringReader problem in CLDC to parse String XML

    hello..
    i'm newbie in java mobile...
    i have problem to parse my XML string to my web service..
    i had develop client mobile to access my web service with KSOAP2, and in the first time, i devlop in CDC not CLDC, so there is no problem when i use some of java.io, i use java.io.StringReader to parse my string XML...
    the code i use in CDC when using java.io.StringReader is like this :
    XmlPullParser parser = new KXmlParser();
    String a = "<n1:ClientHeader xmlns:n1=\"http://www.myweb.web.id\">" +
                            "<n1:ClientUser>" + client.user + "</n1:ClientUser>" +
                            "<n1:ClientIP>" + client.ip + "</n1:ClientIP>" +
                    "</n1:ClientHeader >";     
    parser.setInput(new StringReader(a));
    Document doc = new Document();
    doc.parse(parser);
    Element headSoap = new Element();        
    headSoap = doc.getRootElement();      then, i use this code in CLDC, the error was found, becouse java.io.StringReader in CLDC not found.
    so, my question is ...
    any solution to solve my problem when i have string which the value is in XML, like in my code before, and i want to parse it to kxml2.kdom.Element, how..?
    please help me...

    hello..
    i'm newbie in java mobile...
    i have problem to parse my XML string to my web service..
    i had develop client mobile to access my web service with KSOAP2, and in the first time, i devlop in CDC not CLDC, so there is no problem when i use some of java.io, i use java.io.StringReader to parse my string XML...
    the code i use in CDC when using java.io.StringReader is like this :
    XmlPullParser parser = new KXmlParser();
    String a = "<n1:ClientHeader xmlns:n1=\"http://www.myweb.web.id\">" +
                            "<n1:ClientUser>" + client.user + "</n1:ClientUser>" +
                            "<n1:ClientIP>" + client.ip + "</n1:ClientIP>" +
                    "</n1:ClientHeader >";     
    parser.setInput(new StringReader(a));
    Document doc = new Document();
    doc.parse(parser);
    Element headSoap = new Element();        
    headSoap = doc.getRootElement();      then, i use this code in CLDC, the error was found, becouse java.io.StringReader in CLDC not found.
    so, my question is ...
    any solution to solve my problem when i have string which the value is in XML, like in my code before, and i want to parse it to kxml2.kdom.Element, how..?
    please help me...

  • Problem in parsing an xml using DOM parser.

    Hi,
        I have created an action block for client.
        it  takes a xml file present on D drive and generates a pdf by parsing the xml file.
        My code was working perfectly fine till yesterday.
    But now i getting , [INFO ]: Error-- Premature end of file.  org.xml.sax.SAXParseException: Premature end of file.
    But xml is perfectly fine. Also the code work from eclipse.
    Need some inputs on this.
    Regards,
    Vishal Jadhav
    Edited by: vishal jadhav on Jan 23, 2009 9:49 AM

    Vishal,
    what exactly did you change? How do you call the action block? What version/Support package/Build of MII do you use?
    Have you see the following thread? There a user had the same message which was caused by missing credentials.
    [https://forums.sdn.sap.com/click.jspa?searchID=21364701&messageID=6756453]
    Michael
    Edited by: Michael Otto on Jan 23, 2009 11:57 AM

  • Problem in parsing a xml string using dom parser

    i want to parse a Xml String using a Dom parser......the parse function in dom parser takes only input stream as argument.......so i made the code as
    InputStream inputstream = new StringBufferInputStream(XmlData) ;
    InputSource inputSource = new InputSource(inputstream );
    but saxexception is coming and also warning called
    "java.io.StringBufferInputStream in java.io has been deprecated"
    please help me.........

    i want to parse a Xml String using a Dom
    parser......the parse function in dom parser takes
    only input stream as argument.......This is not true of the DOM parser in Java 1.4. So you might want to get rid of your old parser and replace it by something more current. Or perhaps you are using 1.4 and you just didn't read all of the API docs.

  • Parsing a XML file using Jdom-Problem.

    Hi all,
    I am reposting it as I was told to format the code and send it again.
    I am trying to parse a xml file using a jdom java code.This code works fine if I remove xmlns attribute in the root element. (I get the expected result) .If the "xmlns" attribute is put in the xml as it should be then the parsing and retrieving returns null. Please tell me how to fix this issue.
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Xml
    <process name="CreateKBEntryService" targetNamespace="http://serena.com/CreateKBEntryService" suppressJoinFailure="yes" xmlns:tns="http://serena.com/CreateKBEntryService" xmlns="http://schemas.xmlsoap.org/ws/2003/03/business-process/" xmlns:bpelx="http://schemas.oracle.com/bpel/extension" xmlns:ora="http://schemas.oracle.com/xpath/extension" xmlns:nsxml0="http://localhost:8080/axis/services/CreateKBEntryService" xmlns:nsxml1="http://DefaultNamespace" xmlns:bpws="http://schemas.xmlsoap.org/ws/2003/03/business-process/">
    <partnerLinks>
    <partnerLink name="client" partnerLinkType="tns:CreateKBEntryService" myRole="CreateKBEntryServiceProvider"/>
    <partnerLink name="CreateKBEntryPartnerLink" partnerLinkType="nsxml0:CreateKBEntryLink" partnerRole="CreateKBEntryProvider"/>
    </partnerLinks>
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~`
    Java:
    import java.io.*;
    import java.util.*;
    import org.jdom.Document;
    import org.jdom.Element;
    import org.jdom.input.SAXBuilder;
    public class sample1 {
    public static void main(String[] args) throws Exception {
    // create a XML parser and read the XML file
    SAXBuilder oBuilder = new SAXBuilder();
    Document oDoc = oBuilder.build(new File("**xml file location**"));
    Element root = oDoc.getRootElement();
    System.out.println(root.getName());
    String tgtns= root.getAttributeValue("targetNamespace");
    System.out.println("tgt ns "+ tgtns);
    List list= root.getChildren("partnerLinks");
    Iterator it1= list.iterator();
    System.out.println("Iterator 1 - "+list.size());
    while(it1.hasNext()){
    Element partnerlinks = (Element)it1.next();
    List list2= partnerlinks.getChildren("partnerLink");
    System.out.println("iterator 2 - "+list2.size());
    }~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Result:
    Without Xmlns in xml file(Expected and correct output)
    process
    tgt ns http://serena.com/CreateKBEntryService
    Iterator 1 - 1//expected and correct result that comes when I remove xmlns attribute from xml
    iterator 2 - 2
    Result with xmlns:
    process
    tgt ns http://serena.com/CreateKBEntryService
    Iterator 1 - 0 //instead of 0 should return 1

    LOL
    This is what you get for working 12 hours straight....
    I changed:
    xmlObject["mydoc"]["modelglue"]["event-handlers"]["event-handler"][i].xmlAttrib utes["name"]<br>
    to:
    #mydoc["modelglue"]["event-handlers"]["event-handler"][i].xmlAttrib utes["name"]#<br>
    xmlObject is the name of my xml object in memory, and then you reference from the root of the xml doc down the chain.
    Sorry for the inconvenience,
    Rich

Maybe you are looking for