Search code examples
javasaxparsersaxparseexception

How to constantly parse an xml log file (SAXParser) which gets dynamically modified in a server? I get Premature end of File error when it's modified


So I am currently working on an internal tool and this problem came up. I am trying to parse this xml file every 10 seconds until it finds a particular tag. However this xml file gets modified as users click and do a bunch of stuff. i have a loop that opens a new fileinputstream and parses the xml file. But I keep getting a Premature End of File error. Does anyone know how to handle this?

  while(notfound)
  {    
       fis = new FileInputStream(new File("c:/tmp/abc.xml"));
       SaxParser.parse(fis, sampleHandler);
       notFound = sampleHandler.checkIfFound();
  }

Solution

  • XML files must be well formed. Each opened tag must be closed.

    XML file may be parsed only after closed by its writer, as a whole.

    XML file isn't a stream, it's a file.

    I you want to parse an XML source as a stream you have to process well formed fragment as records.

    Imagine this structure:

    <log-file>
       <log-record date="...">
          <log-event text="..." />
          <log-event text="..." />
          <log-event text="..." />
       </log-record>
    
       <log-record date="...">
          <log-event text="..." />
          <log-event text="..." />
          <log-event text="..." />
       </log-record>
    
       <log-record date="...">
          <log-event text="..." />
          <log-event text="..." />
          <log-event text="..." />
       </log-record>
    
    <log-file>
    

    A file reader (not a parser) may extract well-formed fragment beginning by . An XML parser may parse the extracted fragment.