SAX serialize XML

Hello,
do you know, if there's a Java class which already parses a file via SAX and outputs the whole file on STDOUT or in another file? I know, it seems it makes no sense, but I need to trim a very large XML file at a fixed point (after perhaps 2000 page-Elements) and write the whole content to another file... so I don't think I have to write a class on my own, just put a counter in the start_element() method and see if it's < 2000.
greetings,
Johannes

Maybe something like:
SAXTransformerFactory fac = (SAXTransformerFactory)TransformerFactory.newInstance();
handler = fac.newTransformerHandler();
Transformer t = handler.getTransformer();
t.setOutputProperty(OutputKeys.METHOD, "xml");
t.setOutputProperty(OutputKeys.INDENT, "yes");
handler.setResult(new StreamResult(new FileOutputStream(filename)));but well, I would need to do something like this:
* {@inheritdoc}
public void startElement(String namespaceURI, String localName, String qName,
      Attributes atts) throws SAXException {
  if (localName.equalsIgnoreCase("page") && counter < ARTICLES) {
    counter++;
  if (counter < ARTICLES) {
}

Similar Messages

  • Sax and xml schema

    Quick question
    Can you use SAX with XML Schema? or SAX will only work on DTD?
    Thanks!

    sax can use either
    i believe all that is needed is calling
    setNamespaceAware(true) on the parser factory to use xsds (along with setValidating(true))

  • XML - 0112 Error on parsing using SAX and xml file in InputSource object.

    I need to parse a XML string and extract some information. I have to use SAX parser. I'm converting hte string to InputSource and then trying to parese.
    i'm getting XML-0112 error, my guess is that it is not able to locate DTD file but i tried hardcoding the whole path in DOCTYPE tag.
    i tried doing setSystemId also but no luck.
    null

    Can you post a simple test case to look at?

  • Sax parse xml bug , I can't figure it out!

    (1) orginal xml file as followings:
    <row>
    <field name="productBundleId">22456</field>
    <field name="localPath">/products/01092008/RealArcade/STD_StonesOfKhufu_NOK6030_EN_v1_0_12.jar</field>
    <field name="description">/products/01092008/RealArcade/STD_StonesOfKhufu_NOK6030_EN_v1_0_12.jad</field>
    </row>
    (2) task parsing the above and and retrieve the value and set it to a javabean:
    (3) Using the SAX as the xml file is very big , about 1M
    * @author mertef
    public class XerseHandlerImp extends DefaultHandler implements MF_CONSTANTS
         List                              m_data               = new ArrayList();
         private CompareSimpleBean     m_csb               = null;
         private String                    m_tmpVal          = "";
         private boolean                    m_id               = false;
         private boolean                    m_jar               = false;
         private boolean                    m_jad               = false;
         private String                    m_whitespace     = "";
         private boolean                    m_character          = false;
         @Override
         public void characters(char[] ch, int start, int length) throws SAXException
    *          // System.out.println(new String(ch,start,length));*
              m_tmpVal = new String(ch, start, length);*
    if (jad) System.out.println(tmpVal);*
         @Override
         public void endElement(String uri, String localName, String name) throws SAXException
              m_character = false;
              if (name.equals(MOVAYA_ROW))
                   m_data.add(m_csb);
              if (name.equals(MOVAYA_FIELD))
                   if (m_id)
                        m_csb.setId(m_tmpVal);
                        m_id = false;
                        m_jar = false;
                        m_jad = false;
                   else if (m_jar)
                        m_csb.setJarPath(m_tmpVal);
                        m_id = false;
                        m_jar = false;
                        m_jad = false;
                   else if (m_jad)
                        m_csb.setJadPath(m_tmpVal);
                        m_id = false;
                        m_jar = false;
                        m_jad = false;
         @Override
         public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException
              m_whitespace = new String(ch, start, length);
    (4) please pay attention to the bold area , the method:
    character()
    I declare a variable "m_character" to decide if the parser don't read content of
    an item in above xml file ,such as
    /products/01092008/RealArcade/STD_StonesOfKhufu_NOK6030_EN_v1_0_12.jar
    (5)error:
    but some time it only reads part of the character contents:
    eg:
    /products/01092008/RealAr
    cade/STD_StonesOfKhufu_UnitedStates_LGCU515_EN_v1_0_12.jad
    It means that they parser comes across some character when parsing,
    but in fact it doesn't.
    You can use println() to monitor the outputs.
    So I need to declare some boolean variable to decide whether all the content of one item has read fully.
    (6)
    May be its a bug, my xml file don't include any special charactor.

    The problem is that the character data might be delivered in multiple chunks, this means that the characters method might be called more than once for the same element.
    One way around this is to create a StringBuilder or something similar in the startElement() method, and fill it with the characters in the characters() method and read it in the endElement() method.
    For more information: http://forum.java.sun.com/thread.jspa?threadID=5255925

  • SAX Parser XML Validation Problems

    Hi,
    I’m having problems getting an xml document to validate within Weblogic 8.1. I am trying to parse a document that references both a dtd and xsd. Both the schema and dtd reference need to be substituted so they use local paths. I specify the schema the parser should use and have created an entityResolver to change the dtd reference.
    When this runs as a standalone app from eclipse the file parses and validates without a problem. When deployed to the app server the process seems to be unable read the contents of the dtd. Its not that it cannot find the file (no FileNotFoundException is thrown but this can be created if I delete the dtd) rather it seems to find no declared elements.
    Initial thought was that the code didn’t have access to read the dtd from its location on disk, to check I moved the dtd to within the deployed war and reference as a resource. The problem still persists.
    Code Snippet:
    boolean isValid = false;
    try {
         // Create and configure factory
    SAXParserFactory factory = SAXParserFactoryImpl.newInstance();
    factory.setValidating(true);
    factory.setNamespaceAware(true);
    // To be notified of validation errors in the XML document,
    // add a custom error handler to the document builder
    PIMSFeedFileValidationHandler handler
    = new PIMSFeedFileValidationHandler();
         // Create and Configure Parser
    SAXParser parser = factory.newSAXParser();
    parser.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
    parser.setProperty(NAMESPACE_PROPERTY_KEY, getSchemaFilePath());
         // Set reader with entityResolver for dtd
    XMLReader xmlReader = parser.getXMLReader();
    xmlReader.setEntityResolver(new SAXEntityResolver(this.dtdPath));
    // convert file to URL, as it is a remote file
    URL url = super.getFile().toURL();
    // Open an input stream and parse
    InputStream is = url.openStream();
    xmlReader.setErrorHandler(handler);
    xmlReader.parse(new InputSource(is));
    is.close();
    // get the result of parsing the document by checking the
    // errorhandler's isValid property
    isValid = handler.isValid();
    if (!isValid) {
    LOGGER.warn(handler.getMessage());
    LOGGER.debug("XML file is valid XML? " + isValid);
    } catch (ParserConfigurationException e) {
    LOGGER.error("Error parsing file", e);
    } catch (SAXException e) {
    LOGGER.error("Error parsing file", e);
    } catch (IOException e) {
    throw new FeedException(e);
    return isValid;
    See stack trace below for a little more info.
    2005-01-28 10:24:09,217 [DEBUG] [file] - Attempting validation of file 'cw501205.wa1.xml' with schema at 'C:/pims-feeds/hansard/schema/hansard-v1-9.xsd'
    2005-01-28 10:24:09,217 [DEBUG] [file] - Entity Resolver is using DTD path file:C:/Vignette/runtime_services/8.1/install/common/nodemanager/
    VgnVCMServer/stage/pims-hansard/pims-hansard.war/WEB-INF/classes/com/morse/pims/cms/feed/sax/ISO-Entities.dtd
    2005-01-28 10:24:09,227 [DEBUG] [file] - Creating InputSource at: file:C:/Vignette/runtime_services/8.1/install/common/nodemanager/VgnVCMServer/stage/pims-hansard/pims-hansard.war/WEB-INF/classes/com/morse/pims/cms/feed/sax/ISO-Entities.dtd
    2005-01-28 10:24:09,718 [WARN ] [file] - org.xml.sax.SAXParseException: Element type "Hansard" must be declared.
    org.xml.sax.SAXParseException: Element type "Session" must be declared.
    org.xml.sax.SAXParseException: Element type "DailyRecord" must be declared.
    org.xml.sax.SAXParseException: Element type "Volume" must be declared.
    org.xml.sax.SAXParseException: Element type "Written" must be declared.
    org.xml.sax.SAXParseException: Element type "WrittenHeading" must be declared.
    org.xml.sax.SAXParseException: Element type "Introduction" must be declared.
    … continues for all the elements in the doc
    2005-01-28 10:24:10,519 [DEBUG] [file] - XML file is valid XML? false
    2005-01-28 10:24:10,519 [WARN ] [file] - Daily Part file 'cw501205.wa1.xml' was not valid XML and was not processed.
    Has anybody seen this behavior before with weblogic and if so how have you resolved the issue.
    Thanks in Advance
    Adam

    Hi David,
    I have checked the ejb-jar.xml file and there is no duplicate values in it and the other things is that the same application is been deployed on OAS 10G and websphere and its working fine. In the forum someone has replied to a similar problem that there is bug in Weblogic 10.3 and its CR no 376292. I am not sure about it, does anyone any information about it.
    Thanks and Regards
    Deepak Dani

  • SAX and XML file, how to?

    Hi,
    I'm going to use JAXP and SAX to read my application XML config file.
    But I'm lost, I don't know how to read the elements.
    How does it function, do I have to put in the startElement() method as many "if" as entitys I need to process?
    And how can I guess if an element belongs (is inside) one element or another?
    Example:
    <program>
    <printer id="xx" type="aa">
    <path> /aa/cc </path>
    </printer>
    <source>
    <path> /aa/bb </path>
    </source>
    </program>
    for this XML, how would you code it? this way?
    startElement (String uri, String localName, String qName, Attributes attributes) {
    if (localname.equals("printer")) {
    //get printer attributes
    } else if (localname.equals("source")) {
    //get source attributes
    thanks!

    i have one sample code through which u can read the elements from xml file.
    // File SaxLister.java
    import java.io.IOException;
    import org.xml.sax.Attributes;
    import org.xml.sax.SAXException;
    import org.xml.sax.XMLReader;
    import org.xml.sax.helpers.DefaultHandler;
    import org.xml.sax.helpers.XMLReaderFactory;
    public class SAXLister {
    public static void main(String[] args) throws Exception
    new SAXLister(args);
    public SAXLister(String[] args) throws SAXException, IOException
    XMLReader parser = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
    // should load properties rather than hardcoding class name
    parser.setContentHandler(new PeopleHandler( ));
    parser.parse(args.length == 1 ? args[0] : "parents.xml");
    /** Inner class provides DocumentHandler
    class PeopleHandler extends DefaultHandler
    boolean parent = false;
    boolean kids = false;
    public void startElement(String nsURI, String localName,
    String rawName, Attributes attributes) throws SAXException {
    // System.out.println("docEvents" + "startElement: " + localName + ","
    // + rawName);
    // Consult rawName since we aren't using xmlns prefixes here.
    if (rawName.equalsIgnoreCase("name"))
    parent = true;
    if (rawName.equalsIgnoreCase("children"))
    kids = true;
    public void characters(char[] ch, int start, int length) {
    if (parent) {
    System.out.println("Parent: " + new String(ch, start, length));
    parent = false;
    } else if (kids) {
    System.out.println("Children: " + new String(ch, start, length));
    kids = false;
    /** Needed for parent constructor */
    public PeopleHandler( ) throws org.xml.sax.SAXException {
    super( );
    // File people.xml
    <?xml version="1.0"?>
    <people>
    <person>
         <name>Ian Darwin</name>
         <email>http://www.darwinsys.com/</email>
         <country>Canada</country>
    </person>
    <person>
         <name>Another Darwin</name>
         <email type="intranet">afd@node1</email>
         <country>Canada</country>
    </person>
    </people>
    I hope this gives u a better understanding of how SAX parser works..
    Kindly note u need xml.jar and xerces.jar in ur classpath to run above program.
    Regards,
    Nikunj

  • SAX / Validating XML file...

    Hello,
    I would like to use the SAX Parser to validate a XML file. So I've downloaded the last sax.jar library and included it in the java 1.4 directory.
    If I set the setvalidating flag to false the parser is working great and i have good results. However I would like to validate the XML file with a XML Schema (that can be accessed using the web). So I saw the Sun tutorial for doing that but have a terrible error ! :
    java.lang.ClassCastException
         at org.apache.xerces.impl.xs.XMLSchemaValidator.reset(XMLSchemaValidator.java:1332)
    and don't understand why, can somebody help me ????
    public class AgentHandler
        extends DefaultHandler
        implements ContentHandler {
      private boolean isAgent;
      private boolean isAgentViaProxy;
      private AgentTable agentTable;
      private String agent;
      private String proxy;
      static final String JAXP_SCHEMA_LANGUAGE =
          "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
      static final String W3C_XML_SCHEMA =
          "http://www.w3.org/2001/XMLSchema";
      static final String JAXP_SCHEMA_SOURCE =
          "http://java.sun.com/xml/jaxp/properties/schemaSource";
      private String representation;
      private StringBuffer content = new StringBuffer();
      MimeBodyPart part;
      Unit currentUnit;
      Consumer nextConsumer;
      protected Object object;
      public AgentTable getAgentTable() {
        ErrorHandler errorHandler = new MyErrorHandler();
        content.setLength(0);
        agentTable = new AgentTable();
        SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setNamespaceAware(true);
        factory.setValidating(true);
        SAXParser saxParser = null;
        try {
          saxParser = factory.newSAXParser();
        catch (ParserConfigurationException ex1) {
          ex1.printStackTrace();
        catch (SAXException ex1) {
          ex1.printStackTrace();
        try {
          saxParser.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
    //agentfile.xml is the XML Schema
    saxParser.setProperty(
         "http://apache.org/xml/properties/schema/external-schemaLocation",
              new File(
              "http://localhost:8080/agentfile.xml"));
        catch (SAXNotSupportedException ex3) {
          ex3.printStackTrace();
        catch (SAXNotRecognizedException ex3) {
          ex3.printStackTrace();
        org.xml.sax.XMLReader xmlReader = null;
        try {
          xmlReader = saxParser.getXMLReader();
        catch (SAXException ex) {
          ex.printStackTrace();
        xmlReader.setContentHandler(this);
        xmlReader.setErrorHandler(errorHandler);
        try {
          xmlReader.parse(new org.xml.sax.InputSource(jamap.share.Constants.homeDir +
                                                      jamap.share.Constants.
                                                      AgentFile));
        catch (SAXException ex2) {
          ex2.printStackTrace();
          System.out.println("Error in parsing the agent.xml file");
        catch (IOException ex2) {
          ex2.printStackTrace();
          System.out.println("Error in parsing the agent.xml file");
        return agentTable;
      }any idea ???
    Thanks...
    PA

    Hello,
    I did some modifications and now it is working : the setproperty was not properly called before....
    Now I have an other problem : in fact the parser doesn't ignore the white spaces, even if I put an ignorableWhitespace method inside the handler : have you any idea to remove these new lines or spaces automatically during the parsing ????
    TU...
    PA
    public AgentTable getAgentTable() {
        ErrorHandler errorHandler = new MyErrorHandler();
        content.setLength(0);
        agentTable = new AgentTable();
        SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setNamespaceAware(true);
        factory.setValidating(true);
        SAXParser saxParser = null;
        try {
          saxParser = factory.newSAXParser();
        catch (ParserConfigurationException ex1) {
          ex1.printStackTrace();
        catch (SAXException ex1) {
          ex1.printStackTrace();
        try {
          saxParser.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
          try {
            saxParser.setProperty(
                "http://java.sun.com/xml/jaxp/properties/schemaSource",
                new org.xml.sax.InputSource("http://localhost:8080/agentfile.xml")
          catch (SAXNotRecognizedException ex4) {
          catch (SAXNotSupportedException ex4) {
        catch (SAXNotSupportedException ex3) {
          ex3.printStackTrace();
        catch (SAXNotRecognizedException ex3) {
          ex3.printStackTrace();
        org.xml.sax.XMLReader xmlReader = null;
        try {
          xmlReader = saxParser.getXMLReader();
        catch (SAXException ex) {
          ex.printStackTrace();
        xmlReader.setContentHandler(this);
        xmlReader.setErrorHandler(errorHandler);
        try {
          xmlReader.parse(new org.xml.sax.InputSource(jamap.share.Constants.homeDir +
                                                      jamap.share.Constants.
                                                      AgentFile));
        catch (SAXException ex2) {
          ex2.printStackTrace();
          System.out.println("Error in parsing the agent.xml file");
        catch (IOException ex2) {
          ex2.printStackTrace();
          System.out.println("Error in parsing the agent.xml file");
        return agentTable;

  • Save/Load with Serializable XML XStream

    I'm working on a simulation model. The first step is the user fills out multiple screens of a wizard-like format with required data. Right now, I have a user create a "site" where all of the wizard information is stored. The Site is independent of the GUI portion. So if something is changed via the wizard, when the user clicks next, the site is updated with the data from the wizard. Likewise, if the site is updated due to a calculation, the wizard must be updated to match the site. Right now, for each panel of the wizard, I have an updateToSite method, and an updateFromSite method for accomplishing these two tasks. So, to save, I call the updateToSite for every panel, and then tell XStream to write the site out. Likewise for loading, I load the site with XStream and then call updateFromSite on every panel.
    If I load an incomplete Site, I get an error and it stops loading any of the information after that error. What would be a good way to make it continue updating the panels with whatever information the site does contain?

    Sch104 wrote:
    If I load an incomplete Site, I get an error and it stops loading any of the information after that error. What would be a good way to make it continue updating the panels with whatever information the site does contain?Stop using XML.
    The reason I say that is, compliant XML parsers are required to stop processing when they encounter the first instance of malformed XML. So if you have a requirement that your site parser should make a best effort to continue in the face of bad data, then using a compliant XML parser is not a good choice. You might find a non-compliant XML parser which tries to paper over malformed data but I haven't heard of such a thing.
    Unless possibly "incomplete" doesn't imply malformed XML but means something else. In which case that analysis doesn't apply and you should just change your code to deal with it, whatever it does mean.

  • Or.xml.sax giving error when parsing character entity

    I am parsing an xml stream using SAX parser using org.xml.sax.*
    When any XML tag say <name>sumit & sumit</name> OR <name>sumit & sumit</name> is parsed it throws the error as :
    org.xml.sax.SAXParseException: XML-0210: (Fatal Error) Unexpected EOF.
    at java.lang.Throwable.fillInStackTrace(Native Method)
    at java.lang.Throwable.fillInStackTrace(Compiled Code)
    at java.lang.Throwable.<init>(Compiled Code)
    at java.lang.Exception.<init>(Compiled Code)
    at org.xml.sax.SAXException.<init>(Compiled Code)
    at org.xml.sax.SAXParseException.<init>(Compiled Code)
    at oracle.xml.parser.v2.XMLParseException.<init>(Compiled Code)
    at oracle.xml.parser.v2.XMLError.flushErrors(Compiled Code)
    at oracle.xml.parser.v2.XMLError.error(Compiled Code)
    at oracle.xml.parser.v2.XMLError.error(Compiled Code)
    at oracle.xml.parser.v2.XMLReader.popXMLReader(Compiled Code)
    at oracle.xml.parser.v2.NonValidatingParser.parseElement(Compiled Code)
    at oracle.xml.parser.v2.NonValidatingParser.parseRootElement(Compiled Co
    de)
    at oracle.xml.parser.v2.NonValidatingParser.parseDocument(Compiled Code)
    at oracle.xml.parser.v2.XMLParser.parse(Compiled Code)
    at com.fidelity.fbrs.general.process.GenericSAXHandler.parse(Compiled Co
    de)
    at com.fidelity.fbrs.general.process.ServiceRequest.processComplexXMLReq
    uest(Compiled Code)
    at com.fidelity.fbrs.general.process.ServiceRequest.processXMLRequest(Co
    mpiled Code)
    at com.fidelity.fbrs.general.process.ServiceRequest.service(Compiled Cod
    e)
    at javax.servlet.http.HttpServlet.service(Compiled Code)
    at org.apache.jserv.JServConnection.processRequest(Compiled Code)
    at org.apache.jserv.JServConnection.run(Compiled Code)
    at java.lang.Thread.run(Compiled Code)
    Please let me the resolution,,,
    Thanks
    Sumit

    Correction:
    you need to escape the & character in your XML file by using &amp; instead of using & directly.

  • XML serialization problem

    Hi,
    I am using Simple 2.4.1 to serialize objects to XML.
    But I could not find out how can I serialize XML which has following DTD.
    <!ELEMENT test (test1 | test2 | test3)>
    Thanks in advance.

    No, DB is just our local crossposting detective. And boy is he efficient at it.
    If you crosspost, at least say so dude. That you want a quick reply is all fine and dandy, but generally people are not responsible enough to post back everywhere they posted as soon as they get an answer, which means people keep wasting time trying to help you. At least give people the chance to ignore you for what you've done.

  • 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 ();

  • Weblogic sample doesn't work properly ( failed to serialize ) ?

    Dear all,
    I am running the sample dom.zip which doesn't run properly from http://dev2dev.bea.com/direct/webservice/index.html.
    Server
    =======================================================
    package examples.dom;
    import org.w3c.dom.Document;
    import org.w3c.dom.Node;
    public final class EchoDom {
    public Document echoDom(Document doc) {
    System.out.println("The dom on the server is[");
    weblogic.xml.babel.stream.DOMInputStream.printNode((Node) doc);
    System.out.println("]");
    return doc;
    Client
    =======================================================
    package examples.dom;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.jar.JarFile;
    import java.util.zip.ZipEntry;
    import javax.xml.rpc.Call;
    import javax.xml.rpc.ParameterMode;
    import javax.xml.rpc.Service;
    import javax.xml.rpc.ServiceFactory;
    import javax.xml.namespace.QName;
    import javax.xml.rpc.handler.HandlerInfo;
    import javax.xml.rpc.handler.HandlerRegistry;
    import javax.xml.soap.SOAPConstants;
    import weblogic.xml.stream.XMLInputStream;
    import weblogic.xml.stream.XMLInputStreamFactory;
    import weblogic.xml.schema.binding.TypeMapping;
    import weblogic.xml.schema.binding.TypeMappingFactory;
    import weblogic.utils.Debug;
    import weblogic.apache.xerces.parsers.DOMParser;
    import java.util.ArrayList;
    import org.w3c.dom.Node;
    import org.w3c.dom.Document;
    import org.w3c.dom.Comment;
    import org.w3c.dom.NodeList;
    import org.w3c.dom.ProcessingInstruction;
    import org.w3c.dom.NamedNodeMap;
    import org.xml.sax.InputSource;
    * @author Copyright (c) 2002 by BEA Systems. All Rights Reserved.
    public final class Client {
    public static Document getDocument(String filename)
    throws Exception
    DOMParser parser = new DOMParser();
    parser.setFeature( "http://apache.org/xml/features/dom/defer-node-expansion",
    false );
    parser.setFeature( "http://xml.org/sax/features/validation",
    false);
    parser.setFeature( "http://xml.org/sax/features/namespaces",
    true);
    parser.setFeature( "http://apache.org/xml/features/validation/schema",
    true);
    parser.parse(weblogic.xml.babel.baseparser.SAXElementFactory.createInputSource(filename));
    Document doc =parser.getDocument();
    return doc;
    public static void main( String[] args ) throws Exception{
    Dom d = new Dom_Impl("http://localhost:7001/dom/EchoDomService?WSDL");
    DomPort port = d.getdomPort();
    Document request = getDocument(args[0]);
    weblogic.xml.babel.stream.DOMInputStream.printNode((Node) request);
    try {
    Document newDoc = port.echoDom(request);
    weblogic.xml.babel.stream.DOMInputStream.printNode((Node) newDoc);
    } catch (javax.xml.rpc.JAXRPCException e) {
    System.out.println(e.getLinkedCause());
    e.getLinkedCause().printStackTrace();
    Run-time Exception
    =========================================================
    C:\JDEV903\jdk\bin\javaw.exe -ojvm -classpath C:\MyStudy\java\WS3\classes;D:\bea\weblogic700\server\lib\webserviceclient+ssl.jar;D:\bea\weblogic700\server\lib\weblogic.jar;C:\JDEV903\jdev\lib\jdev-rt.jar;C:\JDEV903\soap\lib\soap.jar;C:\JDEV903\lib\xmlparserv2.jar;C:\JDEV903\jlib\javax-ssl-1_2.jar;C:\JDEV903\jlib\jssl-1_2.jar;C:\JDEV903\j2ee\home\lib\activation.jar;C:\JDEV903\j2ee\home\lib\mail.jar;C:\JDEV903\j2ee\home\lib\http_client.jar;C:\JDEV903\lib\xmlparserv2.jar;C:\JDEV903\lib\xmlcomp.jar;C:\MyStudy\java\1\dom\client.jar
    -Dweblogic.webservice.verbose=true wl.client.wsServletClient
    java.rmi.RemoteException: web service invoke failed; nested exception is:
    javax.xml.soap.SOAPException: failed to serialize xml:weblogic.xml.schema.binding.SerializationException:
    type mapping lookup failure on class=class weblogic.apache.xerces.dom.DeferredDocumentImpl
    TypeMapping=TYPEMAPPING SIZE=0
    javax.xml.soap.SOAPException: failed to serialize xml:weblogic.xml.schema.binding.SerializationException:
    type mapping lookup failure on class=class weblogic.apache.xerces.dom.DeferredDocumentImpl
    TypeMapping=TYPEMAPPING SIZE=0
         void weblogic.webservice.core.DefaultPart.toXML(javax.xml.soap.SOAPElement, java.lang.Object,
    weblogic.xml.schema.binding.SerializationContext, boolean, javax.xml.rpc.encoding.TypeMapping)
              DefaultPart.java:260
         void weblogic.webservice.core.DefaultMessage.toXML(javax.xml.soap.SOAPMessage,
    java.lang.Object[])
              DefaultMessage.java:455
         java.lang.Object weblogic.webservice.core.DefaultOperation.invoke(java.util.Map,
    java.lang.Object[], java.io.PrintStream)
              DefaultOperation.java:403
         java.lang.Object weblogic.webservice.core.DefaultOperation.invoke(java.util.Map,
    java.lang.Object[])
              DefaultOperation.java:359
         java.lang.Object weblogic.webservice.core.rpc.StubImpl._invoke(java.lang.String,
    java.util.Map)
              StubImpl.java:225
         java.lang.Object examples.dom.EchoDomServicePort_Stub.echoDom(java.lang.Object)
              EchoDomServicePort_Stub.java:33
         void wl.client.wsServletClient.main(java.lang.String[])
              wsServletClient.java:78
    Process exited with exit code 0.
    Please help.
    mindterm

    Hello,
    I just save the dom example a spin and it worked OK for me. RU using the latest service pack? Does the dom.ear build correctly and deploy on the server without errors? Can U see the webservice test page from http://localhost:7001/dom/EchoDomService ?
    Thanks,
    Bruce
    mindterm wrote:
    Dear all,
    I am running the sample dom.zip which doesn't run properly from http://dev2dev.bea.com/direct/webservice/index.html.
    Server
    =======================================================
    package examples.dom;
    import org.w3c.dom.Document;
    import org.w3c.dom.Node;
    public final class EchoDom {
    public Document echoDom(Document doc) {
    System.out.println("The dom on the server is[");
    weblogic.xml.babel.stream.DOMInputStream.printNode((Node) doc);
    System.out.println("]");
    return doc;
    Client
    =======================================================
    package examples.dom;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.jar.JarFile;
    import java.util.zip.ZipEntry;
    import javax.xml.rpc.Call;
    import javax.xml.rpc.ParameterMode;
    import javax.xml.rpc.Service;
    import javax.xml.rpc.ServiceFactory;
    import javax.xml.namespace.QName;
    import javax.xml.rpc.handler.HandlerInfo;
    import javax.xml.rpc.handler.HandlerRegistry;
    import javax.xml.soap.SOAPConstants;
    import weblogic.xml.stream.XMLInputStream;
    import weblogic.xml.stream.XMLInputStreamFactory;
    import weblogic.xml.schema.binding.TypeMapping;
    import weblogic.xml.schema.binding.TypeMappingFactory;
    import weblogic.utils.Debug;
    import weblogic.apache.xerces.parsers.DOMParser;
    import java.util.ArrayList;
    import org.w3c.dom.Node;
    import org.w3c.dom.Document;
    import org.w3c.dom.Comment;
    import org.w3c.dom.NodeList;
    import org.w3c.dom.ProcessingInstruction;
    import org.w3c.dom.NamedNodeMap;
    import org.xml.sax.InputSource;
    * @author Copyright (c) 2002 by BEA Systems. All Rights Reserved.
    public final class Client {
    public static Document getDocument(String filename)
    throws Exception
    DOMParser parser = new DOMParser();
    parser.setFeature( "http://apache.org/xml/features/dom/defer-node-expansion",
    false );
    parser.setFeature( "http://xml.org/sax/features/validation",
    false);
    parser.setFeature( "http://xml.org/sax/features/namespaces",
    true);
    parser.setFeature( "http://apache.org/xml/features/validation/schema",
    true);
    parser.parse(weblogic.xml.babel.baseparser.SAXElementFactory.createInputSource(filename));
    Document doc =parser.getDocument();
    return doc;
    public static void main( String[] args ) throws Exception{
    Dom d = new Dom_Impl("http://localhost:7001/dom/EchoDomService?WSDL");
    DomPort port = d.getdomPort();
    Document request = getDocument(args[0]);
    weblogic.xml.babel.stream.DOMInputStream.printNode((Node) request);
    try {
    Document newDoc = port.echoDom(request);
    weblogic.xml.babel.stream.DOMInputStream.printNode((Node) newDoc);
    } catch (javax.xml.rpc.JAXRPCException e) {
    System.out.println(e.getLinkedCause());
    e.getLinkedCause().printStackTrace();
    Run-time Exception
    =========================================================
    C:\JDEV903\jdk\bin\javaw.exe -ojvm -classpath C:\MyStudy\java\WS3\classes;D:\bea\weblogic700\server\lib\webserviceclient+ssl.jar;D:\bea\weblogic700\server\lib\weblogic.jar;C:\JDEV903\jdev\lib\jdev-rt.jar;C:\JDEV903\soap\lib\soap.jar;C:\JDEV903\lib\xmlparserv2.jar;C:\JDEV903\jlib\javax-ssl-1_2.jar;C:\JDEV903\jlib\jssl-1_2.jar;C:\JDEV903\j2ee\home\lib\activation.jar;C:\JDEV903\j2ee\home\lib\mail.jar;C:\JDEV903\j2ee\home\lib\http_client.jar;C:\JDEV903\lib\xmlparserv2.jar;C:\JDEV903\lib\xmlcomp.jar;C:\MyStudy\java\1\dom\client.jar
    -Dweblogic.webservice.verbose=true wl.client.wsServletClient
    java.rmi.RemoteException: web service invoke failed; nested exception is:
    javax.xml.soap.SOAPException: failed to serialize xml:weblogic.xml.schema.binding.SerializationException:
    type mapping lookup failure on class=class weblogic.apache.xerces.dom.DeferredDocumentImpl
    TypeMapping=TYPEMAPPING SIZE=0
    javax.xml.soap.SOAPException: failed to serialize xml:weblogic.xml.schema.binding.SerializationException:
    type mapping lookup failure on class=class weblogic.apache.xerces.dom.DeferredDocumentImpl
    TypeMapping=TYPEMAPPING SIZE=0
    void weblogic.webservice.core.DefaultPart.toXML(javax.xml.soap.SOAPElement, java.lang.Object,
    weblogic.xml.schema.binding.SerializationContext, boolean, javax.xml.rpc.encoding.TypeMapping)
    DefaultPart.java:260
    void weblogic.webservice.core.DefaultMessage.toXML(javax.xml.soap.SOAPMessage,
    java.lang.Object[])
    DefaultMessage.java:455
    java.lang.Object weblogic.webservice.core.DefaultOperation.invoke(java.util.Map,
    java.lang.Object[], java.io.PrintStream)
    DefaultOperation.java:403
    java.lang.Object weblogic.webservice.core.DefaultOperation.invoke(java.util.Map,
    java.lang.Object[])
    DefaultOperation.java:359
    java.lang.Object weblogic.webservice.core.rpc.StubImpl._invoke(java.lang.String,
    java.util.Map)
    StubImpl.java:225
    java.lang.Object examples.dom.EchoDomServicePort_Stub.echoDom(java.lang.Object)
    EchoDomServicePort_Stub.java:33
    void wl.client.wsServletClient.main(java.lang.String[])
    wsServletClient.java:78
    Process exited with exit code 0.
    Please help.
    mindterm

  • Save GUI components in a XML format

    I am looking for a technoology that can help to create a my own file format using java. That mean currently im working with implementing a mind mapping tool (like mindjet) which will help to do basic mind mapping actions like add, edit, delete topics.
    But I have faced for a ig problem when im saving a created map. because it should save as a new file format and should be able to re-open for editing.
    What I planned is to retrive the GUI component's(elements of the map) properties from the map and write those values to the XML file(using XML DOM or SAX). Then read those saved values and create the GUI components under retrieved data.
    what I want to know is that. Is my approach is correct? or is there any better solution for this matter?
    please clarify me and I would really appreciate your help?
    Regards
    Lakshitha Ranasinghe

    You presumably have some state, in memory, that you want to persist. From your post, though I must confess that the terms you use are not really clear in terms of what type of data you actually want to say, my guess is that you have some graph of objects in memory that you have parsed that you want to serialize and persist and then later deserialize and restore for reuse in a subsequent execution of your program.
    If yes, then your goal is really simple: how do I save the state of my application and then restore it?
    Go to the filesystem: store as a properties file (key-value pairs), Java's default serialization, XML or a totally custom format
    Go do the database: map your object to a proper database table and column (via JDBC or an O/R mapper ala Hibernate), or store what you would have stored in the filesystem in a databaseXML is a valid option. So is a simple properties file. It depends on your requirements. If you are reading from and writing to a Java application, and frequent versioning is not an issue, then Java's default serialization could be a possibility. Going to the database would be the 'enterprise' solution, but requires testing and the successful functioning and communication between two technologies and machines. It depends on your requirements.
    - Saish

  • 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 ();
    }

  • Error handling in parsing XML files.

    Hi.
    Is it possible to handle the error generated by DocumentBuilder elsewhere, as it parses down an XML file? In my test-program, I am parsing (using SAX) an XML file, and testing whether it is valid under a certain schema. If it is valid, I would then generate a console-output tree of the XML file. Otherwise, it would just display the error messages (wherever they are in the XML file).
    This is what I have.
    import java.io.IOException;
    import javax.xml.parsers.*;
    import org.w3c.dom.*;
    import org.xml.sax.SAXException;
    import java.util.*;
    public class XMLTester {
        private Document document;
        private boolean state = true;
        public XMLTester() { }
        public static final void main(String[] args) {
            if ( args.length != 1 ) {
                System.out.println("Usage: java XmlTester myFile.xml");
                System.exit(-1);
            String xmlFile = args[0];
            XMLTester xmltester ;
            xmltester = new XMLTester();  
            xmltester.parseFile(xmlFile);
            if (xmltester.isValidXML() ) {
                 xmltester.printContents());
        public void parseFile(String xmlFile)/* throws ParserConfigurationException,
                            SAXException, IOException */{
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(true);
            factory.setValidating(true);
            factory.setAttribute(
                      "http://java.sun.com/xml/jaxp/properties/schemaLanguage",
                      "http://www.w3.org/2001/XMLSchema");
               DocumentBuilder builder = factory.newDocumentBuilder();
                document = builder.parse(xmlFile);
        } catch (Exception ex) {
             //ex.printStackTrace();
             state = false;
        public boolean isValidXML() {
             return state;
        //..print-out methods here..
    }Thanks!

    Nevermind.. I figured it out after a few thoughts.

Maybe you are looking for

  • Transfer of Files

    My Mac is: Hardware Overview: Machine Name: Power Mac G4 [Digital Audio] Machine Model: PowerMac3,4 CPU Type: PowerPC G4 (2.9) Number Of CPUs: 1 CPU Speed: 533 MHz L2 Cache (per CPU): 1 MB Memory: 640 MB Bus Speed: 133 MHz Boot ROM Version: 4.2.8f1 S

  • How can I get tracks to play faster than normal speed in itunes?

    I have lectures, audio books, and other recordings that I would like to play at faster than normal speed (like 1.5X or 2X normal speed).   I've set all of these recordings as audio books because I read that they have the option to play faster, but, I

  • Protected tab titles are not supported

    Dear Experts, I am working on Tabstrips. I have designed 3 tabs on my tabstrip. when i am looking the screen i am getting a message like "Protected tab titles are not supported". Does anybody knows how to fix this? Thanks, chaitanya.

  • PM Order adding more components

    Hello ALL for example:- (1) i created one PM order and created two MM in component tab so I get one Purchase request  respectively item 01 and 02 . Now the Purchase request has been released and POs are created and did good receipt too. (2) now later

  • Horrible sync with my Music / iTunes Files - Need help!

    Hi, iam very frustrated about options forsyncing media files: BB Link is not working right or it so **bleep** slow, that 40GB needs 2 days to sync!!!! 2 days???? After syncing 1 album that was bought in iTunes - i missed some files on my phone, so al