Is java.xml.parsers.DocumentBuilder Thread Safe?

Does anyone know if the DocumentBuilder is thread safe? Meaning,
can I call the parse(...) methods from several threads simultanously, without getting errors?
I would be happy if anyone can also point me to the documentation that says DocumentBuilder is or isn't thread safe.

My Code Like Such:
public class DigestUtil
private static MessageDigest md_md5 = null;
static
try{
md_md5 = MessageDigest.getInstance("MD5");
}catch(Exception ex)
public static byte[] DigestMD5(byte[] b)
return b==null ? null : md_md5.digest(b);
I Don't Wish to Every Digest, Every Create MessageDigest Instance.

Similar Messages

  • Java.lang.NullPointerException javax.xml.parsers.DocumentBuilder.parse

    Hi all,
    i have a problem by solving an error in my code. The Code is mainly from Ian Darwin.
    The code i am running works with j2sdk1.4.2_04. But now i have to bring it to work with jdk1.6.0_13.
    The code parses xml documents. With small xml documents the code works. With large xml documents i get the following error while running the produced class file.
    Exception in thread "main" java.lang.NullPointerException
    at com.sun.org.apache.xerces.internal.dom.DeferredDocumentImpl.setChunkIndex(DeferredDocumentImpl.java:1944)
    at com.sun.org.apache.xerces.internal.dom.DeferredDocumentImpl.appendChild(DeferredDocumentImpl.java:644)
    at com.sun.org.apache.xerces.internal.parsers.AbstractDOMParser.characters(AbstractDOMParser.java:1191)
    at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.characters(XMLDTDValidator.java:862)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:463)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:807)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:737)
    at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:107)
    at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:225)
    at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:283)
    at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:208)
    at XParse.parse(XParse.java:38)
    at XParse$JFileChooserrv.<init>(XParse.java:119)
    at XParse.main(XParse.java:213)
    I know what a java.lang.NullPointerException mens. But i don't know where i have to look for. Specially i don't know what or where "com.sun.org.apache...." is.
    Is there a package that a have to add to the environment? Can some one tell my where i can find this package?
    I wrote the code for some years ago, 2006 or so. With the knew jdk1.6.0_13 some thinks chance in the environment. Couldn't find what exactly.
    The code has only 215 lines, but some how i can't add it to this Message, because Maximum allowed is only 7500.
    Is there an other Forum, which may is better for my question?

    Here is the code:
    import java.io.*;
    import javax.xml.parsers.*;
    import org.w3c.dom.*;
    import org.xml.sax.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    import javax.swing.*;
    import java.awt.Container;
    import javax.swing.JTextArea;
    * This code is mainly from @author Ian Darwin, [email protected]
    public class XParse {
         /** Convert the file */
         public static void parse(File file, boolean validate) {
              try {
                   System.err.println("");
                   String fileName = file.getAbsolutePath();
                   System.err.println("Parsing " + fileName + "...");
                   // Make the document a URL so relative DTD works.
                   //String uri = new File(fileName).getAbsolutePath();
                   //System.err.println(uri);
                   DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
                   if (validate)
                   f.setValidating(true);
                   DocumentBuilder p = f.newDocumentBuilder();
                   p.setErrorHandler(new MyErrorHandler(System.err));
                   //XmlDocument doc = XmlDocument.createXMLDocument(file);
                   boolean vaild =  p.isValidating();
                   if (vaild) {
                        System.out.println("yes parsing");
                        Document doc = p.parse(file); // <<<< ERROR
                   System.out.println("Parsed OK");
              } catch (SAXParseException ex) {
                   System.err.println("+================================+");
                   System.err.println("|       *SAX Parse Error*        |");
                   System.err.println("+================================+");
                   System.err.println(ex.toString());
                   System.err.println("At line " + ex.getLineNumber());
                   System.err.println("+================================+");
              } /**catch (RuntimeException ex) {
                   System.err.println("+================================+");
                   System.err.println("|       *SAX Parse Error*        |");
                   System.err.println("+================================+");
                   System.err.println(ex.toString());
                   //System.err.println("At line " + ex.getLineNumber());
                   //System.err.println("At line " + ex.getMessage());
                   System.err.println("+================================+");
              }**/ catch (SAXException ex) {
                   System.err.println("+================================+");
                   System.err.println("|          *SAX Error*           |");
                   System.err.println("+================================+");
                   System.err.println(ex.toString());
                   System.err.println("+================================+");
              /*}} catch (SAXNotRecognizedException  ex) {
                   System.err.println(" no SAX");*/
              } catch (ParserConfigurationException ex) {
                   System.err.println(" ???");
               } catch (IOException ex) {
                   System.err.println("+================================+");
                   System.err.println("|           *XML Error*          |");
                   System.err.println("+================================+");
                   System.err.println(ex.toString());
    private static class JFileChooserrv {
         JFileChooserrv(JFrame f, boolean vverabreiten) {
              String openfile;
              String verror;
              boolean validate = true;
              final JFrame frame = f;
              String vFilename = "Z:\\Boorberg\\parsen_vista\\daten";
              //String vFilename = "C:\\";
              File vFile = new File(vFilename);
              final JFileChooser chooser = new JFileChooser(vFile);
              JFileFilter filter = new JFileFilter();
              filter.addType("xml");
              filter.addType("sgml");
              filter.addType("html");
              filter.addType("java");
              filter.setDescription("strukturfiles");
              chooser.addChoosableFileFilter(filter);
              boolean vjeas = true;
              chooser.setMultiSelectionEnabled(vjeas);
              int returnVal = chooser.showOpenDialog(frame);
              if (returnVal == JFileChooser.APPROVE_OPTION) {
                   //Array  filearry[] = chooser.getSelectedFiles();
                   //if (vFile = chooser.getSelectedFiles()) {
                   //File  file[] = chooser.getSelectedFiles();
                   File  vfile[] = chooser.getSelectedFiles();
                   //String openfile = new String();
                   int vlenght = vfile.length;
                   if (vlenght>1) {
                        int x=0;
                        while (x< vlenght) {
                                  parse(vfile[x], validate);
                                  x = x +1;
                   if (vlenght<=1) {
                        File v2file = chooser.getSelectedFile();
                             parse(v2file, validate);
              } else {
                   System.out.println("You did not choose a filesystem           object.");
         System.exit(0);
    private static class JFileFilter extends javax.swing.filechooser.FileFilter {
         protected String description, vnew;
         protected ArrayList<String> exts = new ArrayList<String>();
         protected boolean vtrue;
         public void addType(String s) {
              exts.add(s);
         /** Return true if the given file is accepted by this filter. */
         public boolean accept(File f) {
              // Little trick: if you don't do this, only directory names
              // ending in one of the extentions appear in the window.
              if (f.isDirectory()) {
                   return true;
              } else if (f.isFile()) {
                   Iterator it = exts.iterator();
                   while (it.hasNext()) {
                        if (f.getName().endsWith((String)it.next()))
                             return true;
              // A file that didn't match, or a weirdo (e.g. UNIX device file?).
              return false;
         /** Set the printable description of this filter. */
         public void setDescription(String s) {
              description = s;
         /** Return the printable description of this filter. */
         public String getDescription() {
              return description;
    private static class MyErrorHandler implements ErrorHandler {
            // Error handler output goes here
            private PrintStream out;
            MyErrorHandler(PrintStream out) {
                this.out = out;
             * Returns a string describing parse exception details
            private String getParseExceptionInfo(SAXParseException spe) {
                String systemId = spe.getSystemId();
                if (systemId == null) {
                    systemId = "null";
                String info = "URI=" + systemId +
                    " Line=" + spe.getLineNumber() +
                    ": " + spe.getMessage();
                return info;
            // The following methods are standard SAX ErrorHandler methods.
            // See SAX documentation for more info.
            public void warning(SAXParseException spe) throws SAXException {
                   //System.exit(0);
                //out.println("Warning: " + getParseExceptionInfo(spe));
            public void error(SAXParseException spe) throws SAXException {
                   //System.exit(0);
                String message = "Error: " + getParseExceptionInfo(spe);
                throw new SAXException(message);
            public void fatalError(SAXParseException spe) throws SAXException {
                   //System.exit(0);
                String message = "Fatal Error: " + getParseExceptionInfo(spe);
                throw new SAXException(message);
         public static void main(String[] av) {
              JFrame vframe = new JFrame("chose files to pars");
              boolean vverabreiten = true;
              boolean validate = true;
              JFileChooserrv vdateienwaehlen = new JFileChooserrv(vframe, vverabreiten);
    }The Stack Trace i posted in the last Message. But i couldn't read it, i am not a programmer.

  • Java.util.Locale not thread-safe !

    In multithreading programming, we know that double-checking idiom is broken. But lots of code, even in sun java core libraries, are written using this idiom, like the class "java.util.Locale".
    I have submitted this bug report just now,
    but I wanted to have your opinion about this.
    Don't you think a complete review of the source code of the core libraries is necessary ?
    java.util.Locale seems not to be thread safe, as I look at the source code.
    The static method getDefault() is not synchronized.
    The code is as follows:
    public static Locale getDefault() {
    // do not synchronize this method - see 4071298
    // it's OK if more than one default locale happens to be created
    if (defaultLocale == null) {
    // ... do something ...
    defaultLocale = new Locale(language, country, variant);
    return defaultLocale;
    This method seems to have been synchronized in the past, but the bug report 4071298 removed the "synchronized" modifier.
    The problem is that for multiprocessor machines, each processor having its own cache, the data in these caches are never synchronized with the main memory.
    The lack of a memory barrier, that is provided normally by the "synchronized" modifier, can make a thread read an incompletely initialized Locale instance referenced by the static private variable "defaultlocale".
    This problem is well explained in http://www.javaworld.com/javaworld/jw-02-2001/jw-0209-double.html and other documents about multithreading.
    I think this method must just be synchronized again.

    Shankar, I understand that this is something books and articles about multithreading don't talk much about, because for marketing reasons, multithreading is supposed to be very simple.
    It absolutely not the case.
    Multithreading IS a most difficult topic.
    First, you must be aware that each processor has its own high-speed cache memory, much faster than the main memory.
    This cache is made of a mixture of registers and L1/L2/L3 caches.
    Suppose we have a program with a shared variable "public static int a = 0;".
    On a multiprocessor system, suppose that a thread TA running on processor P1 assign a value to this variable "a=33;".
    The write is done to the cache of P1, but not in the main memory.
    Now, a second thread TB running on processor P2 reads this variable with "System.out.prinln(a);".
    The value of "a" is retrieved from main memory, and is 0 !
    The value 33 is in the cache of P1, not in main memory where its value is still 0, because the cache of P1 has not been flushed.
    When you are using BufferedOutputStream, you use the "flush()" method to flush the buffer, and the "synch()" method to commit data to disk.
    With memory, it is the same thing.
    The java "synchronized" keyword is not only a streetlight to regulate traffic, it is also a "memory barrier".
    The opening brace "{" of a synchronized block writes the data of the processor cache into the main memory.
    Then, the cache is emptied, so that stale values of other data don't remain here.
    Inside the "synchronized" block, the thread must thus retrieve fresh values from main memory.
    At the closing brace "}", data in the processor cache is written to main memory.
    The word "synchronized" has the same meaning as the "sync()" method of FileDescriptor class, which writes data physically to disk.
    You see, it is really a cache communication problem, and the synchronized blocks allows us to devise a kind of data transfer protocol between main memory and the multiple processor local caches.
    The hardware does not do this memory reconciliation for you. You must do it yourself using "synchronized" block.
    Besides, inside a synchronized block, the processor ( or compiler ) feels free to write data in any order it feels most appropriate.
    It can thus reorder assignments and instruction.
    It is like the elevator algorithm used when you store data into a hard disk.
    Writes are reordered so that they can be retrieved more efficiently by one sweep or the magnetic head.
    This reordering, as well as the arbitrary moment the processor decides to reconciliate parts of its cache to main memory ( if you don't use synchronized ) are the source of the problem.
    A thread TB on processor P2 can retrieve a non-null pointer, and retrieve this object from main memory, where it is not yet initialized.
    It has been initialized in the cache of P1 by TA, though, but TB doen't see it.
    To summarize, use "synchronized" every time you access to shared variables.
    There is no other way to be safe.
    You get the problem, now ?
    ( Note that this problem has strictly nothing to do with the atomicity issue, but most people tend to mix the two topics...
    Besides, as each access to a shared variable must be done inside a synchronized block, the issue of atomicity is not important at all.
    Why would you care about atomicity if you can get a stale value ?
    The only case where atomicity is important is when multiple threads access a single shared variable not in synchronized block. In this case, the variable must be declared volatile, which in theory synchronizes main and cache memory, and make even long and double atomic, but as it is broken in lots of implementation, ... )

  • Javax.xml.parsers.DocumentBuilder to skip invalid XML characters?

    Hi,
    I convert XML files into flat files. In doing so I call the API DocumentBuilder.parse(File f). If the XML file f contains an invalid XML character, the API throws a SAXException.
    My question is: while I know that certain invalid XML chars are not part of the data and therefore can be safely ignored in the conversion, is there a way to tell the API to skip those chars?

    Nope. Compliant XML parsers are required to parse the XML as it is and not to "repair" it in any way. Your best option is not to have badly-formed XML in the first place, so if you are the one generating the XML, you should fix that process. But if you have bozo customers generating it, and you can't make them do it right, then pre-process the XML to drop the bad characters.

  • Java.lang.reflect.Constructor thread safe ?

    When you have a Constructor object in Java.
    Is calling the newInstance method on the same Constructor object from multiple threads safe.
    Or is this not thread safe leading to wrongly constructed objects?

    ejp wrote:
    And as Constructors are immutable, it's hard to see how it's going to get altered.Constructors are basically immutable, but they have at least one state which can make the difference between newInstance working or failing.
    As you can see in the following example, setAccessible() is not something you would want to set to different values in different threads.
    import java.lang.reflect.Constructor;
    public class Main {
        public static void main(String... args) throws Exception {
            Constructor cons = Private.class.getDeclaredConstructor();
            cons.setAccessible(false);
            try {
                System.out.println("cons.isAccessible()= " + cons.isAccessible());
                cons.newInstance();
                throw new AssertionError("IllegalAccessException expected");
            } catch (IllegalAccessException expected) {
                // ignored
            cons.setAccessible(true);
            System.out.println("cons.isAccessible()= " + cons.isAccessible());
            cons.newInstance();
    class Private {
        private Private() {
    }

  • Java XML parsers for Sun J2ME, Sun KVM

    Here is a list of "small" XML parsers.
    Some are specifically for the J2ME platform / Sun KVM:
    kXML
    http://kxml.enhydra.org/
    NanoXML
    http://nanoxml.sourceforge.net/
    TinyXML
    http://www.gibaradunn.srac.org/tiny/index.shtml
    MinML
    http://www.wilson.co.uk/xml/minml.htm
    XMLtp
    http://sourceforge.net/projects/jxmltp/
    Al Sutton XML parser
    http://sourceforge.net/projects/asxmlp/
    Also:
    JSR 118 is a specification for the "Mobile Information Device
    Next Generation"
    http://www.jcp.org/jsr/detail/118.jsp
    The JSR 118 group is considering adding a "small, efficient XML parser to enable platform-independent data exchange" to MIDP.

    Fastparser is a 25Ko parser : http://www.japisoft.com/fastparser
    Best regards,
    A.Brillant

  • Is java.nio.channels.FileLock thread safe ?

    Hello,
    I want to lock a file in exclusive mode. The 1.4.2 doc says the followings:
    File locks are held on behalf of the entire Java virtual machine. They are not suitable for controlling access to a file by multiple threads within the same virtual machine.
    File-lock objects are safe for use by multiple concurrent threads.
    I'm confused. If They are not suitable for controlling access to a file by multiple threads within the same virtual machine, How can they be safe for use by multiple concurrent threads ?
    thanks in advance...

    I think it means that you still need to synchronize your threads around the code that obtains the lock and writes data to the file.

  • URGENT:  javax.xml.parsers.DocumentBuilder.parse() method issue

    Hi folks,
    I have an urgent parsing problem. I developed an app with JDK1.4 and now it needs to run on JDK1.3.1. The problem is this:
    If I use the DocumentBuilder.parse() method shipped with JDK1.4 it will parse a document containing namespaces WITHOUT a namespace declaration in the root element. However, since XML support doesn't ship with JDK1.3.1 I need to use JAXP. If I try this with the DocumentBuilder.parse() version shipped with JAXP (latest version) the parse method throws a NullPointerException. If I put the namespace declaration in the document it will parse fine. I tried setting the DocumentBuilderFactory.setNamespaceAware() explicitly to false (should be the default) but no luck. Any ideas other than adding the declaration (long story why I don't want it there...)
    thanks

    example, with declaration of namespace:
    <?xml version="1.0" encoding="UTF-8"?>
    <pre:root xmlns:inn="http://blablabla/inn/version/1.0/">
    <pre:metadata>
    <pre:dublin-core>
    <pre:title>mytitle</pre:title>
    <pre:description>mydesc</pre:description>
    <pre:creator>bjmann</pre:creator>
    </inn:dublin-core>
    </pre:root>
    example, without declaration:
    <?xml version="1.0" encoding="UTF-8"?>
    <pre:root>
    <pre:metadata>
    <pre:dublin-core>
    <pre:title>mytitle</pre:title>
    <pre:description>mydesc</pre:description>
    <pre:creator>bjmann</pre:creator>
    </inn:dublin-core>
    </pre:root>
    this may help...

  • XSD size and Java XML Parsers (specifically SAX)

    Does the size of XSD matter in terms of performace runtime. I would like to create an XSD as one contract that houses all non-mandatory elements so the resulting xml out of this will use similar structure but wont use all of the XSD elements.
    Is there a problem with such an XSD which will be 1000 or more elements as far as Java parsing is concerned
    Pl. let me knwo thanks

    I do a lot of work with an international standard -- S1000D -- for documentation and technical manuals. It has 58 schema files (10 that are main files that are referenced by an XML file, and the other 48 get imbedded as needed). It does not slow down the parsing of files by any noticable amount.
    Dave Patterson

  • How can I parser a String with javax.xml.parsers.DocumentBuilder?

    Normally the DocumentBuilder can parse files, InputSource,InputStream or uri. but what if I want to parse an editing String the user created in an EditPane or JTextComponent?

    new InputSource(new StringReader(theString))

  • Java XMl parsing problems

    i have an xml sturcture as shown below:
    <cnv:conversion xmlns:cnv="urn:ssis-conv" xmlns:xsql="urn:oracle-xsql">
    <cnv:roottag support="yes" destag="xfw:script">
    <cnv:addattr name="debug" value="no" />
    <cnv:addattr name="xmlns:xfw" value="urn:scb-xfw-v2" />
    </cnv:roottag>
    <xsql:query support="yes" destag="xfw:genxml">
    <connection support="no" />
    <row-element support="yes" destag="row-name" />
    <rowset-element support="yes" destag="rowset-name" />
    <id-attribute support="no" />
    <tag-case support="no" />
    <null-indicator support="no" />
    <cnv:addattr name="debug" value="yes" />
    <cnv:addattr name="Attribute1" value="Value1" />
    </xsql:query>
    <xsql:no-rows-query support="no" child="no" />
    <responsedata support="no" child="yes" />
    <responsedata2 support="no" child="yes" />
    <page destag="page1" support="yes">
    <connection support="no" /> <debug destag="MyDebug" />
    <cnv:addattr name="tt" value="t1" />
    </page>
    <xsql:set-page-param support="yes" destag="setpageparam">
    <name destag="myname" />
    </xsql:set-page-param>
    <xsql:set-page-param-local support="yes" destag="Myset-page-param-local">
    <name destag="mylocalname" />
    </xsql:set-page-param-local>
    </cnv:conversion>
    I want this xml to be validated by the dom parser which i had done and its showing it as valid XML.
    If there are any repeating tags like:
    <cnv:conversion xmlns:cnv="urn:ssis-conv" xmlns:xsql="urn:oracle-xsql">
    <cnv:conversion xmlns:cnv="urn:ssis-conv" xmlns:xsql="urn:oracle-xsql">
    <cnv:roottag support="yes" destag="xfw:script">
    <cnv:addattr name="debug" value="no" />
    <cnv:addattr name="xmlns:xfw" value="urn:scb-xfw-v2" />
    </cnv:roottag>
    <xsql:query support="yes" destag="xfw:genxml">
    <connection support="no" />
    <row-element support="yes" destag="row-name" />
    <rowset-element support="yes" destag="rowset-name" />
    <id-attribute support="no" />
    <tag-case support="no" />
    <null-indicator support="no" />
    <cnv:addattr name="debug" value="yes" />
    <cnv:addattr name="Attribute1" value="Value1" />
    </xsql:query>
    <xsql:no-rows-query support="no" child="no" />
    <responsedata support="no" child="yes" />
    <responsedata2 support="no" child="yes" />
    <page destag="page1" support="yes">
    <connection support="no" /> <debug destag="MyDebug" />
    <cnv:addattr name="tt" value="t1" />
    </page>
    <xsql:set-page-param support="yes" destag="setpageparam">
    <name destag="myname" />
    </xsql:set-page-param>
    <xsql:set-page-param-local support="yes" destag="Myset-page-param-local">
    <name destag="mylocalname" />
    </xsql:set-page-param-local>
    </cnv:conversion>
    </cnv:conversion>
    or like this....................
    <cnv:conversion xmlns:cnv="urn:ssis-conv" xmlns:xsql="urn:oracle-xsql">
    <cnv:roottag support="yes" destag="xfw:script">
    <cnv:addattr name="debug" value="no" />
    <cnv:addattr name="xmlns:xfw" value="urn:scb-xfw-v2" />
    </cnv:roottag>
    <cnv:roottag support="yes" destag="xfw:script">
    <cnv:addattr name="debug" value="no" />
    <cnv:addattr name="xmlns:xfw" value="urn:scb-xfw-v2" />
    </cnv:roottag>
    <xsql:query support="yes" destag="xfw:genxml">
    <connection support="no" />
    <row-element support="yes" destag="row-name" />
    <rowset-element support="yes" destag="rowset-name" />
    <id-attribute support="no" />
    <tag-case support="no" />
    <null-indicator support="no" />
    <cnv:addattr name="debug" value="yes" />
    <cnv:addattr name="Attribute1" value="Value1" />
    </xsql:query>
    <xsql:no-rows-query support="no" child="no" />
    <responsedata support="no" child="yes" />
    <responsedata2 support="no" child="yes" />
    <page destag="page1" support="yes">
    <connection support="no" /> <debug destag="MyDebug" />
    <cnv:addattr name="tt" value="t1" />
    </page>
    <xsql:set-page-param support="yes" destag="setpageparam">
    <name destag="myname" />
    </xsql:set-page-param>
    <xsql:set-page-param-local support="yes" destag="Myset-page-param-local">
    <name destag="mylocalname" />
    </xsql:set-page-param-local>
    </cnv:conversion>
    My java code is shown below :
    import java.io.*;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import org.w3c.dom.*;
    public class sample2
    public void processXML(String path)
    File docFile=new File(path);
    Document doc=null;
    try
    DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance(); DocumentBuilder db=dbf.newDocumentBuilder();
    doc=db.parse(docFile);
    catch(IOException ioe)
    System.out.println("cant find file");
    catch(Exception e)
    System.out.println("Error has occured");
    Element root=doc.getDocumentElement();
    NodeList children=root.getChildNodes();
    StringBuffer sbuf=new StringBuffer();
    for(Node child=root.getFirstChild(); child!=null; child=child.getNextSibling())
    if(child.getNodeType()==child.TEXT_NODE) sbuf.append(child.getNodeValue()) ;
    else if(child.getNodeType()==child.ELEMENT_NODE) if(child.getChildNodes()!=null)
    getnodes(child, sbuf);
    public void getnodes(Node Child, StringBuffer sbf)
    NodeList children=Child.getChildNodes();
    if(children.getLength() > 0)
    System.out.println(children.getLength() + Child.getNodeName());
    for(Node child=Child.getFirstChild(); child!=null;child=child.getNextSibling())
    if(child.getNodeType()==child.TEXT_NODE) sbf.append((child.getNodeValue()).trim());
    else if(child.getNodeType()==child.ELEMENT_NODE)
    if(child.getChildNodes()!=null)
    getnodes(child, sbf); sbf.append(";");
    public static void main(String[] args)
    testxml txml=new testxml();
    txml.processXML("E:\\Naresh\\conversion_fxsql.xml");
    can any body tell me how to validate the repeating tags (as i dont have dtd for this xml )with the given code.... if any one of the tags are repeating it should raise an exception thats its not a valid xml
    Thanks in advance
    Regards
    Bunny

    I suggest you create a DTD or a XSD file to validate your existing XML document, because it's easier that i looks, and will help in future changes.
    If you want to do it in Java code, you can always store each line of the XML file in some form (like a class) in a List, and the each time you read a line, you compare with everything on the list.
    But don't go that way, make a XSD file

  • JAVA XML Parsing

    i have an xml sturcture as shown below:
    <cnv:conversion xmlns:cnv="urn:ssis-conv" xmlns:xsql="urn:oracle-xsql">
         <cnv:roottag support="yes" destag="xfw:script">
              <cnv:addattr name="debug" value="no" />
              <cnv:addattr name="xmlns:xfw" value="urn:scb-xfw-v2" />
         </cnv:roottag>
         <xsql:query support="yes" destag="xfw:genxml">
              <connection support="no" />
              <row-element support="yes" destag="row-name" />
              <rowset-element support="yes" destag="rowset-name" />
              <id-attribute support="no" />
              <tag-case support="no" />
              <null-indicator support="no" />
              <cnv:addattr name="debug" value="yes" />
              <cnv:addattr name="Attribute1" value="Value1" />
         </xsql:query>
         <xsql:no-rows-query support="no" child="no" />
         <responsedata support="no" child="yes" />
         <responsedata2 support="no" child="yes" />
         <page destag="page1" support="yes">
              <connection support="no" /> <debug destag="MyDebug" />
              <cnv:addattr name="tt" value="t1" />
         </page>
         <xsql:set-page-param support="yes" destag="setpageparam">
              <name destag="myname" />
         </xsql:set-page-param>
         <xsql:set-page-param-local support="yes" destag="Myset-page-param-local">
              <name destag="mylocalname" />
         </xsql:set-page-param-local>
    </cnv:conversion>
    I want this xml to be validated by the dom parser which i had done and its showing it as valid XML.
    If there are any repeating tags like:
    <cnv:conversion xmlns:cnv="urn:ssis-conv" xmlns:xsql="urn:oracle-xsql">
    <cnv:conversion xmlns:cnv="urn:ssis-conv" xmlns:xsql="urn:oracle-xsql">
         <cnv:roottag support="yes" destag="xfw:script">
              <cnv:addattr name="debug" value="no" />
              <cnv:addattr name="xmlns:xfw" value="urn:scb-xfw-v2" />
         </cnv:roottag>
         <xsql:query support="yes" destag="xfw:genxml">
              <connection support="no" />
              <row-element support="yes" destag="row-name" />
              <rowset-element support="yes" destag="rowset-name" />
              <id-attribute support="no" />
              <tag-case support="no" />
              <null-indicator support="no" />
              <cnv:addattr name="debug" value="yes" />
              <cnv:addattr name="Attribute1" value="Value1" />
         </xsql:query>
         <xsql:no-rows-query support="no" child="no" />
         <responsedata support="no" child="yes" />
         <responsedata2 support="no" child="yes" />
         <page destag="page1" support="yes">
              <connection support="no" /> <debug destag="MyDebug" />
              <cnv:addattr name="tt" value="t1" />
         </page>
         <xsql:set-page-param support="yes" destag="setpageparam">
              <name destag="myname" />
         </xsql:set-page-param>
         <xsql:set-page-param-local support="yes" destag="Myset-page-param-local">
              <name destag="mylocalname" />
         </xsql:set-page-param-local>
    </cnv:conversion>
    </cnv:conversion>
    or like this....................
    <cnv:conversion xmlns:cnv="urn:ssis-conv" xmlns:xsql="urn:oracle-xsql">
         <cnv:roottag support="yes" destag="xfw:script">
              <cnv:addattr name="debug" value="no" />
              <cnv:addattr name="xmlns:xfw" value="urn:scb-xfw-v2" />
         </cnv:roottag>
    <cnv:roottag support="yes" destag="xfw:script">
              <cnv:addattr name="debug" value="no" />
              <cnv:addattr name="xmlns:xfw" value="urn:scb-xfw-v2" />
         </cnv:roottag>
         <xsql:query support="yes" destag="xfw:genxml">
              <connection support="no" />
              <row-element support="yes" destag="row-name" />
              <rowset-element support="yes" destag="rowset-name" />
              <id-attribute support="no" />
              <tag-case support="no" />
              <null-indicator support="no" />
              <cnv:addattr name="debug" value="yes" />
              <cnv:addattr name="Attribute1" value="Value1" />
         </xsql:query>
         <xsql:no-rows-query support="no" child="no" />
         <responsedata support="no" child="yes" />
         <responsedata2 support="no" child="yes" />
         <page destag="page1" support="yes">
              <connection support="no" /> <debug destag="MyDebug" />
              <cnv:addattr name="tt" value="t1" />
         </page>
         <xsql:set-page-param support="yes" destag="setpageparam">
              <name destag="myname" />
         </xsql:set-page-param>
         <xsql:set-page-param-local support="yes" destag="Myset-page-param-local">
              <name destag="mylocalname" />
         </xsql:set-page-param-local>
    </cnv:conversion>
    or any row is being repeated it not a valid XML....
    my java code is :
    My java code is shown below :
    import java.io.*;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import org.w3c.dom.*;
    public class sample2
         public void processXML(String path)
              File docFile=new File(path);
              Document doc=null;
              try
                   DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();                     DocumentBuilder db=dbf.newDocumentBuilder();
                   doc=db.parse(docFile);
              catch(IOException ioe)
                   System.out.println("cant find file");
              catch(Exception e)
                   System.out.println("Error has occured");
              Element root=doc.getDocumentElement();
              NodeList children=root.getChildNodes();
              StringBuffer sbuf=new StringBuffer();
              for(Node child=root.getFirstChild(); child!=null; child=child.getNextSibling())
                   if(child.getNodeType()==child.TEXT_NODE)                sbuf.append(child.getNodeValue()) ;
                   else if(child.getNodeType()==child.ELEMENT_NODE)                if(child.getChildNodes()!=null)
                   getnodes(child, sbuf);
    public void getnodes(Node Child, StringBuffer sbf)
         NodeList children=Child.getChildNodes();
         if(children.getLength() > 0)
              System.out.println(children.getLength() + Child.getNodeName());
         for(Node child=Child.getFirstChild(); child!=null;child=child.getNextSibling())
              if(child.getNodeType()==child.TEXT_NODE) sbf.append((child.getNodeValue()).trim());
         else if(child.getNodeType()==child.ELEMENT_NODE)
         if(child.getChildNodes()!=null)
              getnodes(child, sbf); sbf.append(";");
    public static void main(String[] args)
         testxml txml=new testxml(); txml.processXML("E:\\Naresh\\conversion_fxsql.xml");
    can any body tell me how to validate the repeating tags with the given code.... if any one of the tags are repeating it should raise an exception thats its not a valid xml
    Thanks in advance
    Regards
    Bunny

    The first problem about this document is that it contains a space at the very first position whereas <?xml... must appear at the very beginning of a document. I think this was the cause of the parsing fault.
    Also you have a dash before the root element of the document, which is illegal.

  • Java XML and podcasts

    Hi all,,
    Im just looking for some help with a java xml passer program. Im trying to create a program that will read specific tags and the values that are represented by these tags in the xml file..I have found the following code
    import java.io.File;
    import org.w3c.dom.Document;
    import org.w3c.dom.*;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.DocumentBuilder;
    import org.xml.sax.SAXException;
    import org.xml.sax.SAXParseException;
    public class ReadAndPrintXMLFile{
    public static void main (String argv []){
    try {
    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
    Document doc = docBuilder.parse (new File("book.xml"));
    // normalize text representation
    doc.getDocumentElement ().normalize ();
    System.out.println ("Root element of the doc is " + doc.getDocumentElement().getNodeName());
    NodeList listOfPersons = doc.getElementsByTagName("person");
    int totalPersons = listOfPersons.getLength();
    System.out.println("Total no of people : " + totalPersons);
    for(int s=0; s<listOfPersons.getLength() ; s++){
    Node firstPersonNode = listOfPersons.item(s);
    if(firstPersonNode.getNodeType() == Node.ELEMENT_NODE){
    Element firstPersonElement = (Element)firstPersonNode;
    NodeList firstNameList = firstPersonElement.getElementsByTagName("first");
    Element firstNameElement = (Element)firstNameList.item(0);
    NodeList textFNList = firstNameElement.getChildNodes();
    System.out.println("First Name : " + ((Node)textFNList.item(0)).getNodeValue().trim());
    NodeList lastNameList = firstPersonElement.getElementsByTagName("last");
    Element lastNameElement = (Element)lastNameList.item(0);
    NodeList textLNList = lastNameElement.getChildNodes();
    System.out.println("Last Name : " + ((Node)textLNList.item(0)).getNodeValue().trim());
    NodeList ageList = firstPersonElement.getElementsByTagName("age");
    Element ageElement = (Element)ageList.item(0);
    NodeList textAgeList = ageElement.getChildNodes();
    System.out.println("Age : " + ((Node)textAgeList.item(0)).getNodeValue().trim());
    }//end of if clause
    }//end of for loop with s var
    }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 ();
    //System.exit (0);
    }//end of main
    }Im trying to develop this code to work with podcast xml files..Im having a few issuses with this program.. Is there anyone out there that has created a program like this that works with podcast xml files??
    Anyone got any suggestions.Please.

    XML and XSL transformations can be done using most languages and in Java there is strong support for these techniques.
    It worries me a little bit that you ask this question though. XML and XSL are no more than a tool to solve SOME problems, but I get the idea that you want to put them on your resume as if they are your main talent. The tool set of the developer is much broader than just some techniques to format and transform data, you need to be able to solve problems in the most efficient way possible, not limiting yourself to only a handful of techniques that you just happen to know a lot about.
    What I am trying to say is: it is always good to have knowledge of these techniques, but don't go thinking it is going to guarantee you a job.

  • Javax.xml.parsers Parser Failes at URGENT..URGENT.

    Hai,
    I am using JAVA PARSER to parse my xml file. My XML file is :
    <QUERY>SELECT * FROM EMP WHERE EMP_DATE > 18/10/2000</QUERY>.
    My Sample Code is:
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.DocumentBuilder;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.DOMException;
    factory = DocumentBuilderFactory.newInstance();
    builder = factory.newDocumentBuilder();
    fistream = new FileInputStream(fileName);
    document = builder.parse(fistream);
    e=document.getDocumentElement();
    curElm = (Element)nodeList.item(0);
    return_Value =((Text)curElm.getFirstChild()).getData().trim();
    Giving wrong output:
    SELECT * FROM EMP WHERE EMP_DATE
    Activally, I had to get
    SELECT * FROM EMP WHERE EMP_DATE > 18/10/2000.
    I do not know what's went wrong ?
    Please help me. It is very urgent to my project.
    Thanks a lot
    Regards
    Suresh

    hi,
    <, >, &, " and ' are XML control characters and do not belong to the data an XML document reflects. if you want to use these special characters, try a different notation, i.e. < > & " or &apos; as in
    <element>this is an <element> tag</element>
    sincerely, Michael

  • Contents of META-INF/services/javax.xml.parsers.DocumentBuilderFactory?

    I am currently working on an applet that solves Sudoku puzzles, allowing you to build your own in a Constructor and then solve them in a seperate Solver. To do this, we are implementing the puzzles files as XML documents.
    I have the code completely complied and on the server ( [sudoku.unl.edu|sudoku.unl.edu]) and it runs NEARLY perfectly, however when trying to access the server to save the xml code, the apache error_log presents this message: "File does not exist: classes/META-INF/services
    /javax.xml.parsers.DocumentBuilderFactory"
    Looking at the Java Doc here it says that the program should look for that in the jars. I am unsure of exactly how the applet is interacting with the server, but typing "java -version" yields:
    java version "1.6.0_11"
    Java(TM) SE Runtime Environment (build 1.6.0_11-b03)
    Java HotSpot(TM) 64-Bit Server VM (build 11.0-b16, mixed mode)Notably, the code works PERFECTLY in NetBeans, contacting the server using SCP and uploading the file and such, so the code doesn't seem to be the problem, unless I need to direct the DocumentBuilder code somehow. This is the code that I believe is causing the trouble (I have tried to include all relevant imports that are in my code):
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import org.xml.sax.SAXException;
    DocumentBuilderFactory factoryBuilder;
              DocumentBuilder builder;
              Document doc;
              Element docElement;
              try
                   factoryBuilder  = DocumentBuilderFactory.newInstance( );
                   builder = factoryBuilder.newDocumentBuilder();
                   doc = builder.parse( indexLocation );
                   docElement = doc.getDocumentElement();
                   NodeList children = docElement.getChildNodes();          
                   for(int i =0; i < children.getLength(); i++)
                        if(children.item(i).getNodeType() == 1)
                             if((children.item(i).getNodeName()).equals("directory"))
                                  if ((children.item(i).getAttributes().getNamedItem("name").getNodeValue()).equals("UsersInput")) {
                                       Node firstChild = findNodeItem(children.item(i), "Difficulty0.." + this.upperField.getText());
                                       Node secondChild = findNodeItem(firstChild, "Level" + this.levelField.getText());
                                       Node thirdChild = findNodeItem(secondChild, (String)suTypeList.getSelectedItem());
                                       Element newFile = doc.createElement("file");
                                       newFile.setAttribute("name", fileName);                              
                                       thirdChild.appendChild(newFile);                              
                   SshParameters params = new SshParameters("cse.unl.edu", "consystlab","A/tutti");
                // create new Scp instance
                Scp scp = new Scp(params);
                // register event listener
                scp.addListener(this);
                // establish connection
                scp.connect();
                   TransformerFactory tFactory = TransformerFactory.newInstance();
                   Transformer transformer = tFactory.newTransformer();
                   DOMSource source = new DOMSource(doc);
                   StringWriter sw=new StringWriter();
                   StreamResult result = new StreamResult(sw);
                   transformer.transform(source, result);
                   String xmlString=sw.toString();
                // upload file
                  scp.upload(xmlString.getBytes(), indexPath, "libraryIndex.xml");
                 // disconnect
                scp.disconnect();
              catch (IOException e)
                   System.out.println("IO ERROR7");
                   System.out.println(e);
              catch (TransformerException tranE){
                   tranE.printStackTrace();               
              catch (ParserConfigurationException e)
                   System.out.println("IO ERROR8");
                   System.out.println(e);
              catch (SAXException e)
                   System.out.println("IO ERROR9");
                   System.out.println(e);
              }So my question is, what exactly are the contents of the file in the META-INF/services folder? I have manually created this file in my classes directory, where the program is searching. When I place text in it, it appends the text with .class and searches for that file, but doesn't seem to do anything with the file. I attempted directing it to the "DocumentBuilderFactory.class" file that I extracted from the classes.jar included with the JDK.
    I feel like all I need is this file to contain the correct content and the code will FINALLY work, but I have not been able to find anything out there on it.
    Thank for you for your help, sorry this was such a long message.
    -Jason

    Thanks!
    Thanks for the fast reply. I don't know if I made my point clear.
    I do not want to determine the parser by myself. I want the client system use the default parser, so I do not have the hit of downloading the fairly large parser jar.
    However, I want it not to do an empty request to the server for nothing. This turn around time kills an Applet. I want a fast loading applet!
    I'll go in trial and error mode, when I find the time next week.
    Thanks again, I appreciate it!
    K<o>

Maybe you are looking for