XML closing tags missing throws exception with SAX Parser

Hey,
I'm trying to create an XML Document from some HTML.
I am getting this exception:
[Fatal Error] :1:334: The element type "input" must be terminated by the matching end-tag "</input>".
Exception in thread "main" java.lang.RuntimeException: org.xml.sax.SAXParseException: The element type "input" must be terminated by the matching end-tag "</input>".
     at server.XMLUtils.createDocument(XMLUtils.java:76)The xml is like this:
<html>
<input name="s" size="5">
</html>Is there some setting I can change in the parser to make it ignore missing closing tags?
Here is my current code
     public static Document createDocument(InputStream is) {
          try {
               Document doc;
               DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
               DocumentBuilder db = dbf.newDocumentBuilder();
               doc = db.parse(is);
               doc.getDocumentElement().normalize();
               is.close();
               return doc;
          } catch (Exception e) {
               throw new RuntimeException(e);
     }Thanks

Nether wrote:
Hey,
The xml is like this:
<html>
<input name="s" size="5">
</html>
That is not XML. It might qualify as HTML. An XML file would be
<html>
<input name="s" size="5"/>
</html>Winston

Similar Messages

  • Dreamweaver bug?: XML closing tag ( _/ ) is flawed.

    This is the original code:
    <_bug>hello</_bug>
    And this is how it's opened by DW (CS4):
    <_bug>hello<_bug>
    Sorry but I can't try it in CS5

    Hello Murray! Thanks for your help. The title of my post is wrong and the underscore it's really an underscore. Just copy-paste the code i wrote, save it as .xml, and then open it with DW. You will see the slash of the closing tag is missing   But if you open it with notepad, for example, you will see the slash again.
    The problem comes when you save the file with DW... Your slash will be deleted forever.

  • Throw Exception with Severity Severe on ALBPM 5.7

    Hello,
    Would like to know if there is a way of throwing an exception with severity severe so that the calling PAPI call will get the error back.
    Thank you in advance your you suggestions.
    Edited by: user8913595 on Mar 3, 2011 11:54 AM

    Using admin center, able to get the string to be used in directory.properties.
    FYI, the string looks like below,
    directory.default.url=oracle://customURL:0/schema=bpmdirectory,customURL=jdbc:oracle:thin:@(DESCRIPTION = (LOAD_BALANCE = on)(FAILOVER = on)(ADDRESS = (PROTOCOL = TCP)(HOST = DB_HOST1)(PORT=1521))(ADDRESS = (PROTOCOL = TCP)(HOST = DB_HOST2)(PORT=1521)) (CONNECT_DATA = (SERVICE_NAME = BPMDB.DOMAIN.COM) (FAILOVER_MODE = (TYPE = SELECT) (METHOD = BASIC))))

  • How to Create XML file with SAX parser instead of DOM parser

    HI ALL,
    I am in need of creating an XML file by SAX parser ONLY. As far as my knowledge goes, we can use DOM for such purpose(by using createElement, creatAttribute ...). Can anyone tell me, is there any way to create an XML file using SAX Parser only. I mean, I just want to know whether SAX provides any sort of api for Creatign an element, attribute etc. I know that SAX is for event based parsing. But my requirement is to create an XML file from using only SAX parser.
    Any help would be appreciated
    Thanx in advance
    Kaushik

    Hi,
    You must write a XMLWriter class yourself, and that Class extends DefaultHandle ....., the overwrite the startElement(url, localName, qName, attributeList), startDocument(), endElement().....and so on.
    in startElement write your own logic about how to create a new element and how to create a Attribute list
    in startDocument write your own logic about how to build a document and encodeType, dtd....
    By using:
    XMLWriter out = new XMLWriter()
    out.startDocument();
    Attribute attr1 = new Atribute();
    attr1.add("name", "value");
    out.startElement("","","Element1", attr1);
    Attribute attr2 = new Atribute();
    attr2.add("name", "value");
    out.startElement("","","Element2", attr2);
    out.endElement("","","Element2");
    out.endElement("","","Element1");
    out.endDocument();

  • Problem with sax parser

    Hello..
    I have the following problem. When I parse an xml document with blank spaces and numbers with decimals, its sometimes comes out as one string and sometimes as two, for example "First A" sometimes comes out as "First" and "A" and sometimes as "First A", which is how its stored in the xml file. Same with numbers like 19.20. Im enclosing a little of my code..
    public void characters(char buf[], int offset, int len)
    throws SAXException
    if (textBuffer != null) {
    SaveString = ""+textBuffer;
    if(i>-1)
    numbers = SaveString;
    Whats wrong and how do I fix it.
    Best Regards Dan
    PS I have more code, in data and out data if needed.Ds

    Hello,
    I do not know if this is your problem, yet please find hereafter an excerpt of the SAX API:
    public void characters(char[] ch,
                           int start,
                           int length)
                    throws SAXException
    ... SAX parsers may return all contiguous character data in a single chunk, or they may split it into several chunks;...
    ... Note that some parsers will report whitespace in element content using the ignorableWhitespace method rather than this one (validating parsers must do so)...
    In other words, I am afraid that your issue is the "standard behaviour" of a SAX parser.
    I hope it helps.

  • How to  HTMLEditorKit's parser with Sax Parser?

    How does one do it? I know you need to override getParser method. But the ParserCallback's handleStartTag, handleEndTag etc expect a parameter pos of type int. Needless to say, the pos is undocumented. I have not idea what value to pass. If I pass -1, I get some exceptions. Anyone has a working code snippet which he/she can share?
    Thanks a bunch
    Narayanan

    ParserCallback is like an event listener.
    Take for example a MouseListener. You don't invoke the mouseClicked(...) method. You add code to the mouseClicked(...) method to respond to the mouseClicked event.
    Same thing with the ParserCallback. You don't invoke the handleStartTag(...) method. As the ParserCallback is parsing an HTML Document it will notify you when it finds a start tag in the Document. It tells you the tag it found and the position of the tag in the Document.
    Here is a simple example that just displays all the text in the document:
    import java.io.*;
    import java.net.*;
    import javax.swing.text.html.parser.*;
    import javax.swing.text.html.*;
    public class ParserCallbackText extends HTMLEditorKit.ParserCallback
         public void handleText(char[] data, int pos)
              System.out.println( data );
         public static void main(String[] args)
              throws Exception
              Reader reader = getReader(args[0]);
              ParserCallbackText parser = new ParserCallbackText();
              new ParserDelegator().parse(reader, parser, true);
         static Reader getReader(String uri)
              throws IOException
              // Retrieve from Internet.
              if (uri.startsWith("http:"))
                   URLConnection conn = new URL(uri).openConnection();
                   return new InputStreamReader(conn.getInputStream());
              // Retrieve from file.
              else
                   return new FileReader(uri);
    }

  • Probem with SAX parser

    Hi to averybody!
    I'm trying to parse a xml file using SAX parser but I found a problem.
    When the method
    public void characters(char[] ch, int start, int length)
    I try to print the content in this way:
    for (int i = start; i <= length; i++)
    System.out.print(ch);
    but nothing is printed except except in 2 cases.
    the file parsed start like this:
    <BatchMaint xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://www.ncr.com/bosphoenix/WSMaintenance_5.0.xsd">
    <Id>1000950</Id>
    <DateTime>2009-02-11T11:37:09</DateTime>
    <FromPC>TD185008-1J7</FromPC>
    <FromAppl>BatchToPosWS.dll</FromAppl>
    <FromVersion>001.000.000.000</FromVersion>
    the method print only "1000950" and "2009-02-11T11:37:09".
    Has somebody any idea how fix the problem??

    From the API documentation for the characters() method:
    "The Parser will call this method to report each chunk of character data. SAX parsers may return all contiguous character data in a single chunk, or they may split it into several chunks; however, all of the characters in any single event must come from the same external entity so that the Locator provides useful information."

  • Code to read xml file  and display that data using sax parser

    Hai
    My problem I have to read a xml file and display the contents of the file on console using sax parser.

    here you go

  • CreateStatement throws exception with OracleXADataSource

              I am having problem getting transaction running with Oracle driver. I am using the
              driver supplied by Oracle. I could not make the weblogic driver working (it gave
              errors at the startup time).
              createStatement throws an exception.
              Sample code, stacktrace/error and config.xml settings are attached.
              It would be great, if somebody can indicate the problem.
              Also, I would appreciate, I can find how DataSource for Weblogic's XA Oracle driver
              can be set.
              Thanks,
              Vinay
              [error_wl.txt]
              

              Hi Vinay,
              A couple of things to note. Oracle 8.1.6's driver has a bug that
              does not accept foreign Xid, and thus cannot be used with any 3rd
              party vendor's Tranaction Manager, including WLS. Oracle 8.1.7's
              driver has fixed this problem, but they have threading issues.
              We have worked around the threading issues in Silversword, but
              not in WLS 6.0 release. For now, the only Oracle XA driver we
              recommend is Weblogic's jDriver for Oracle.
              -- Priscilla Fung, BEA Systems, Inc.
              "Vinay" <[email protected]> wrote:
              >
              >
              >
              >I am having problem getting transaction running with Oracle
              >driver. I am using the
              >driver supplied by Oracle. I could not make the weblogic
              >driver working (it gave
              >errors at the startup time).
              >createStatement throws an exception.
              >Sample code, stacktrace/error and config.xml settings
              >are attached.
              >
              >It would be great, if somebody can indicate the problem.
              >Also, I would appreciate, I can find how DataSource for
              >Weblogic's XA Oracle driver
              >can be set.
              >
              >Thanks,
              >
              >Vinay
              

  • Reading xml file with sax parser: unknown protocol: c

    Hi,
    I've been googling around, and the best I can find is that the file name:
    File test = new File("lib/test/parseTest/validate-test.xml");should be a url:
    File test = new File("File://lib/test/parseTest/validate-test.xml");but I'm working on a linux machine and can't put "File://c:/pathToFile/file.xml"
    Also, I did some testing and I can read a small xml file with just a few elements, but on large complex files, I get that error.
    anyone ever run into this before?
    bp
    Edited by: badperson on Nov 1, 2008 2:19 PM

    badperson wrote:
    I've been googling around, and the best I can find is that the file name:
    File test = new File("lib/test/parseTest/validate-test.xml");should be a url:
    File test = new File("File://lib/test/parseTest/validate-test.xml");
    No, that's wrong. The parameter for that constructor is a file path (relative or absolute). Not a URL. You must have misunderstood whatever you read.
    but I'm working on a linux machine and can't put "File://c:/pathToFile/file.xml"What kind of a Linux machine is this which has a C drive? You must have misunderstood whoever told you to do that.

  • Problem with SAX parser - entity must finish with a semi-colon

    Hi,
    I'm pretty new to the complexities of using SAXParserFactory and its cousins of XMLReaderAdapter, HTMLBuilder, HTMLDocument, entity resolvers and the like, so wondered if perhaps someone could give me a hand with this problem.
    In a nutshell, my code is really nothing more than a glorified HTML parser - a web page editor, if you like. I read in an HTML file (only one that my software has created in the first place), parse it, then produce a Swing representation of the various tags I've parsed from the page and display this on a canvas. So, for instance, I would convert a simple <TABLE> of three rows and one column, via an HTMLTableElement, into a Swing JPanel containing three JLabels, suitably laid out.
    I then allow the user to amend the values of the various HTML attributes, and I then write the HTML representation back to the web page.
    It works reasonably well, albeit a bit heavy on resources. Here's a summary of the code for parsing an HTML file:
          htmlBuilder = new HTMLBuilder();
    parserFactory = SAXParserFactory.newInstance();
    parserFactory.setValidating(false);
    parserFactory.setNamespaceAware(true);
    FileInputStream fileInputStream = new FileInputStream(htmlFile);
    InputSource inputSource = new InputSource(fileInputStream);
    DoctypeChangerStream changer = new DoctypeChangerStream(inputSource.getByteStream());
    changer.setGenerator(
       new DoctypeGenerator()
          public Doctype generate(Doctype old)
             return new DoctypeImpl
             old.getRootElement(),
                              old.getPublicId(),
                              old.getSystemId(),
             old.getInternalSubset()
          resolver = new TSLLocalEntityResolver("-//W3C//DTD XHTML 1.0 Transitional//EN", "xhtml1-transitional.dtd");
          readerAdapter = new XMLReaderAdapter(parserFactory.newSAXParser().getXMLReader());
          readerAdapter.setDocumentHandler(htmlBuilder);
          readerAdapter.setEntityResolver(resolver);
          readerAdapter.parse(inputSource);
          htmlDocument = htmlBuilder.getHTMLDocument();
          htmlBody = (HTMLBodyElement)htmlDocument.getBody();
          traversal = (DocumentTraversal)htmlDocument;
          walker = traversal.createTreeWalker(htmlBody,NodeFilter.SHOW_ELEMENT, null, true);
          rootNode = new DefaultMutableTreeNode(new WidgetTreeRootNode(htmlFile));
          createNodes(walker); However, I'm having a problem parsing a piece of HTML for a streaming video widget. The key part of this HTML is as follows:
                <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
                  id="client"
            width="100%"
            height="100%"
                  codebase="http://fpdownload.macromedia.com/get/flashplayer/current/swflash.cab">
                  <param name="movie" value="client.swf?user=lkcl&stream=stream2&streamtype=live&server=rtmp://192.168.250.206/oflaDemo" />
             etc....You will see that the <param> tag in the HTML has a value attribute which is a URL plus three URL parameters - looks absolutely standard, and in fact works absolutely correctly in a browser. However, when my readerAdapter.parse() method gets to this point, it throws an exception saying that there should be a semi-colon after the entity 'stream'. I can see whats happening - basically the SAXParser thinks that the ampersand marks the start of a new entity. When it finds '&stream' it expects it to finish with a semi-colon (e.g. much like and other such HTML characters). The only way I can get the parser past this point is to encode all the relevant ampersands to %26 -- but then the web page stops working ! Aaargh....
    Can someone explain what my options are for getting around this problem ? Some property I can set on the parser ? A different DTD ? Not to use SAX at all ? Override the parser's exception handler ? A completely different approach ?!
    Could you provide a simple example to explain what you mean ?
    Thanks in anticipation !

    You probably don't have the ampersands in your "value" attribute escaped properly. It should look like this:
    value="client.swf?user=lkcl&stream=...{code}
    Most HTML processors (i.e. browsers) will overlook that omission, because almost nobody does it right when they are generating HTML by hand, but XML processors won't.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Problem with SAX parser with String format

    hi, all I have the next problem:
    I try to parse xml file with success, I write next code:
    ====================
    my_class saxUms = new my_class();
    File file = new File( "c:\\my_try_Response.xml" );
    InputSource src1 = new InputSource( new FileInputStream( file ) );
    XMLReader rdr = XMLReaderFactory.createXMLReader( "org.apache.xerces.parsers.SAXParser" );          rdr.setContentHandler( saxUms );
    rdr.parse(src1);
    ===================
    but when I try to parse the same in string variable, I write:
    ===================
    my_class saxUms = new my_class();
    StringReader strr = new StringReader(my_str);
    InputSource intt = new InputSource(strr);
    XMLReader prs= XMLReaderFactory.createXMLReader( "org.apache.xerces.parsers.SAXParser" );
    prs.setContentHandler(saxUms);
    prs.parse(intt);
    ===================
    and error occurs:
              "Exception: java.lang.ClassCastException: java.lang.StringBuffer"
    how to fix the problem?
    Thank you for collaboration!

    where does the exception stack trace say the error is occurring?

  • TransformerHandler throws OutOfMemoryError with large xml files

    i'm using TransformerHandler to convert any content to SAX events and transform it using XSLT into an XML file.
    the problem is that for large amount of content i get a OutOfMemoryError.
    it seams that the content is kept in memory and only flushed when i call handler.endDocument();
    i tried using auto flush writers as the Result, or call the flush() method myself, but nothing.
    here is the example - pls help!
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.sax.SAXTransformerFactory;
    import javax.xml.transform.sax.TransformerHandler;
    import javax.xml.transform.stream.StreamResult;
    import javax.xml.transform.stream.StreamSource;
    import org.xml.sax.helpers.AttributesImpl;
    public class Test
          * test handler memory usage
          * @param loops no of loops - when large enogh - OutOfMemoryError !!!
          * @param xsltFilePath xslt file
          * @param targetXmlFile output xml file
          * @throws Exception
         public static void testHandlerMemUsage(int loops, String xsltFilePath, String targetXmlFile)throws Exception
              //verify SAX support
              TransformerFactory factory = TransformerFactory.newInstance();
              if(!factory.getFeature(SAXTransformerFactory.FEATURE))
                   throw new UnsupportedOperationException("SAX tranformations not supported");
              TransformerHandler handler=
                   ((SAXTransformerFactory)factory).newTransformerHandler(new StreamSource(xsltFilePath));
              handler.setResult(new StreamResult(targetXmlFile));
              handler.startDocument();
              handler.startElement(null,"root","root",new AttributesImpl());
              //loop
              for(int i=0;i<loops;i++)
                   handler.startElement(null,"el-"+i,"el-"+i,new AttributesImpl());
                   handler.characters("value".toCharArray(),0,"value".length());
                   handler.endElement(null,"el-"+i,"el-"+i);
              handler.endElement(null,"root","root");
              //System.out.println("end document");
              //only after endDocument() starts to print..
              handler.endDocument();
              //System.out.println("ended document");
         public static void main(String[] args)throws Exception
              System.out.println("--starting..");
              testHandlerMemUsage(500000,"/copy.xslt","/testHandlerMemUsage.xml");
              System.out.println("--we are still here -- increase loops..");
    }

    Did you try increasing memeory when starting java with the -Xmx parameter? You know that java uses only 64MB by default, so you might need to increase it to e.g. 256MB for your XML to work.

  • Can I parse non-wellformed XML with SAX at all?

    Hi all,
    i was wondering whether its possible at all to parse XML that is not well formed with SAX.
    e.g. A HTML file that doesnt close tags and stuff like that.
    I tried implementing the fatal() method of the Handler in a a way that it consumes the exception but does not rethrow it.
    Also I tried setting the validation property to false. Both with no success.
    Any help would be appriciated.
    thx
    philipp

    Your experiments tell you the answer.
    If you have HTML tag soup, why not just run it through JTidy or HTMLTidy to make it into well-formed XHTML?

  • Java SAX parser. How to get raw XML code of the currently parsing event?

    Java SAX parser, please need a clue how to get the raw XML code of the currently parsing event... needed for logging, debugging purposes.
    Here's and example, letting me clarify exactly what i need: (see the comments in source)
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
         //..Here... or maybe somewhere elsewhere I need on my disposal the raw XML code of
         //..every XML tags received from the XML stream. I need simply to write it down
         //..in a log file, for debugging purposes, while parsing. Can anyone give me a suggestion
         //..how can i implement such logging while the SAX parser only returns me the tagname and
         //..attributes. While parsing I want to log the XML code for every tag in
         //..its 'pure form', like it is comming from the server directly on the
         //..socket's input reader.
         if ("p".equals(qName)) {
              etc...
    }Than you in advance.

    YES!
    I've solved my problem using class RecordingInputStream that wraps the InputStream
    here is the class source code:
    import java.io.ByteArrayOutputStream;
    import java.io.FilterInputStream;
    import java.io.InputStream;
    import java.io.IOException;
    * @author Unknown
    class RecordingInputStream  extends  FilterInputStream {
         protected ByteArrayOutputStream sink;
        RecordingInputStream(InputStream in) {
            this(in, new ByteArrayOutputStream());
        RecordingInputStream(InputStream in, ByteArrayOutputStream sink) {
            super(in);
            this.sink = sink;
        public synchronized int read() throws IOException {
            int i = in.read();
            sink.write(i);
            return i;
        public synchronized int read(byte[] buf, int off, int len) throws IOException {
            int l = in.read(buf, off, len);
            sink.write(buf, off, l);
            return l;
        public synchronized int read(byte[] buf) throws IOException {
            return read(buf, 0, buf.length);
        public synchronized long skip(long len) throws IOException {
            long l = 0;
            int i = 0;
            byte[] buf = new byte[1024];
            while (l < len) {
                i = read(buf, 0, (int)Math.min((long)buf.length, len - l));
                if (i == -1) break;
                l += i;
            return l;
        byte[] getBytes() {
            return sink.toByteArray();
        void resetSink() {
            sink.reset();
    } Then here is the initialization before use with SAX:
    this.psock = new Socket(this.profile.httpServer, Integer.parseInt(this.profile.httpPort));
    this.out = new PrintWriter(this.psock.getOutputStream(), true);
    this.ris=new RecordingInputStream(this.psock.getInputStream());
    this.in=new BufferedReader(new InputStreamReader(this.ris));
    try {
         this.parser = SAXParserFactory.newInstance().newSAXParser();
         this.parser.parse(new InputSource(this.in),new XMLCommandsHandler());
    catch (IOException ioex) {  }
    catch (Exception ex) {  }Then the handler class looks like this (it will be an inner class, so you can access ris, from the parent class):
    class XMLCommandsHandler extends DefaultHandler {
         public void startDocument() throws SAXException {
              //...nothing
         public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
              // BEGIN - Synchronized logging of raw XML source code in parallel with SAX parsing :)
              byte[] bs=ris.getBytes();
              logger.warn(new String(bs));
              ris.resetSink();
              // End logging
              if ("expectedTagThatTriggersMeToDoSomething".equals(qName)) {
                   //...Do smth.
    }Edited by: patladj on Jul 3, 2008 12:30 PM

Maybe you are looking for

  • Install ORACLE 8.1.6 and 9i on HP UNIX 11.20 (11i)

    Hi, When I install ORACLE 8.1.6 and/or 9i on HP UNIX 11i (11.20, hardware: i2000 workstation), I got the following error message: Exception thrown from action: make Exception Name: MakefileException Exception String: Error in invoking target nnfgt.o

  • IDVD will not burn DVD or preview

    I made a DVD in IDVD and burned a DVD last week. I went back into IDVD to replace some photos and movies and when I tried to burn another DVD, the wheel spins and the progress screen comes up but does not progress or burn. I tried different DVDs but

  • Application windows do not respond - help please!

    Hi everyone At first I should say that I did search for this topic in search forum section but all of the cases related to freezing windows app. do not match my problem. So recently something strange occurs: my app windows freezes (I mean I can't clo

  • NetBIOS name in shared column?

    Can anyone explain why my G5's NetBIOS name (WINS) shows up on the shared column when I am logged on to my powerbook or IMAC (both wireless)? The G5 is connected to the Airport Extreme via ethernet. Just updated several days ago to 10.5.1 and this ju

  • Installing tom tom western europe to iphone 3g

    downloaded this app to my ipad.then loaded it back on to imac 10.5.8.then tried to load it to my iphone and it keeps coming up with error 0xE8000004.has any one come across this.