Java - DOM Parsing - Reg

I am trying to get the value of the element - <e> -from an xml file which looks as below
<a>
<b>
<c> </c>
<d>
<e>SampleValue</e>
</d>
</b>
</a>
and I am using the Sun DOM1 parser. I am not sure what I missing I have tried using something like below
NodeList list = document.getElementByeTagName("b");
Node node = list.item(0);
NodeList list2 = node.getChildNodes();
for(i=0;i<list2.getLength();i++){ 
Node tempN = (Node)list2.item(i)
//I trying to get value of element "e"
System.out.print(tempN.getNodeValue());
I think I am missing something,could anyone ..help me out.
Thanks
ej

String eValue=document.getElementsByTagName("e").item(0).getFirstChild().getNodeValue();

Similar Messages

  • Java DOM Parser (XML)

    Could someone please give me a link where I can find a example of a DOM parser, w3c. That shows how to parse an xml string or file and build the tree then access parts of it? I cant find a basic example anywhere!

    Check this
    http://java.sun.com/xml/jaxp/dist/1.1/docs/tutorial/dom/1_read.html

  • Context change by DOM parsing Java Mapping in XI

    Hi Team,
    I would like to know that how can I handle Context Change by DOM Parser Java Mapping in XI.?
    Suppose  the source XML structure I have like below:
    <?xml version="1.0" encoding="UTF-8"?>
    <ns0:Header xmlns:ns0="urn:bp:xi:hr:edm:test:100">
       <FileName>
          <filesub>
             <subname>a</subname>
             <subname>b</subname>
             <subname>c</subname>
          </filesub>
       </FileName>
       <FileName>
          <filesub>
             <subname>d</subname>
             <subname>e</subname>
             <subname>f</subname>
          </filesub>
       </FileName>
    </ns0:Header>
    Where the field FileName can occur maximum thrice(0...3) but the subname field is (0....unbounded) but in the target source I would like to have as given below:
    <?xml version="1.0" encoding="UTF-8" ?>
    - <MT_Test4 xmlns="urn:bp:xi:hr:edm:test:100">
    - <Header>
      <FileName>a</FileName>
      <FileName1>d</FileName1>
        </Header>
    - <Header>
      <FileName>b</FileName>
      <FileName1>e</FileName1>
       </Header>
    Header>
      <FileName>c</FileName>
      <FileName1>f</FileName1>
       </Header>
    </MT_Test4>
    That means the first value from every context of the source field is forming my first and second value in my target first context.Thensecond value from every context is forming my 1st and 2nd value of my target 2nd context and finally 3rd value of every context is forming my 1st and 2nd value of my target 3rd context.Is this possible to done through DOM parsing or we have to do it by UDF only?

    Hi Atanu,
        In my last post I gave an alogorithm to solve the mapping problem. Here is the complete program for the mapping.
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.util.Map;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.transform.stream.StreamResult;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import com.sap.aii.mapping.api.StreamTransformation;
    import com.sap.aii.mapping.api.StreamTransformationException;
    public class DOMParser1  implements StreamTransformation{
         public void execute(InputStream in, OutputStream out)
                   throws StreamTransformationException {
              try
                   DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
                   DocumentBuilder builderel=factory.newDocumentBuilder();
                   /input document in form of XML/
                   Document docIn=builderel.parse(in);
                   /document after parsing/
                   Document docOut=builderel.newDocument();
                   TransformerFactory tf=TransformerFactory.newInstance();
                   Transformer transform=tf.newTransformer();
                   Element root,child,child1=null;
                   Node textChild;
                   NodeList l;
                   int i,n1,j,div,k;
                   String s[];
                   root=docOut.createElement("MT_Test4");
                   root.setAttribute("xmlns","urn:bp:xi:hr:edm:test:100");
                   l=docIn.getElementsByTagName("subname");
                   n1=l.getLength();
                   s=new String[n1];
                   for(i=0;i<n1;++i)
                             s<i>=l.item(i).getFirstChild().getNodeValue();
                   l=docIn.getElementsByTagName("filesub");
                   div=l.getLength();
                   j=n1/div;
                   for(i=0,k=0;i<j;++i)
                        child1=docOut.createElement("Header");
                        root.appendChild(child1);
                        child=docOut.createElement("FileName");
                        textChild=docOut.createTextNode(s[k]);
                        child.appendChild(textChild);
                        child1.appendChild(child);
                        child=docOut.createElement("FileName1");
                        textChild=docOut.createTextNode(s [ k + j ]);
                        child.appendChild(textChild);
                        child1.appendChild(child);
                        ++k;
                   docOut.appendChild(root);
                   transform.transform(new DOMSource(docOut), new StreamResult(out));     
              catch(Exception e)
                   e.printStackTrace();
         public void setParameter(Map arg0) {
         public static void main(String[] args) {
              try{
                   DOMParser1 genFormat=new DOMParser1();
                   FileInputStream in=new FileInputStream("C:/Apps/my dw/sdnq/apps.xml");
                   FileOutputStream out=new FileOutputStream("C:/Apps/my dw/sdnq/tgt1.xml");
                   genFormat.execute(in,out);
              catch(Exception e)
                   e.printStackTrace();
    source ->  apps.xml
    <?xml version="1.0" encoding="UTF-8" ?>
    - <ns0:Header xmlns:ns0="urn:bp:xi:hr:edm:test:100">
    - <FileName>
    - <filesub>
      <subname>a</subname>
      <subname>b</subname>
      <subname>c</subname>
      </filesub>
      </FileName>
    - <FileName>
    - <filesub>
      <subname>d</subname>
      <subname>e</subname>
      <subname>f</subname>
      </filesub>
      </FileName>
      </ns0:Header>
    target structure ->  tgt1.xml
    <?xml version="1.0" encoding="UTF-8" ?>
    - <MT_Test4 xmlns="urn:bp:xi:hr:edm:test:100">
    - <Header>
      <FileName>a</FileName>
      <FileName1>d</FileName1>
      </Header>
    - <Header>
      <FileName>b</FileName>
      <FileName1>e</FileName1>
      </Header>
    - <Header>
      <FileName>c</FileName>
      <FileName1>f</FileName1>
      </Header>
      </MT_Test4>
    Hope this helps
    one more thing  in this line "textChild=docOut.createTextNode(s k + j );"   somehow the the third braces one opening  before k and one closing after j is missing for unknown reasons. Please correct it when you actually run this code.
    regards
    Anupam
    Edited by: anupamsap on Mar 7, 2011 12:47 PM

  • Parsing an XML using DOM parser in Java in Recursive fashion

    I need to parse an XML using DOM parser in Java. New tags can be added to the XML in future. Code should be written in such a way that even with new tags added there should not be any code change. I felt that parsing the XML recursively can solve this problem. Can any one please share sample Java code that parses XML recursively. Thanks in Advance.

    Actually, if you are planning to use DOM then you will be doing that task after you parse the data. But anyway, have you read any tutorials or books about how to process XML in Java? If not, my suggestion would be to start by doing that. You cannot learn that by fishing on forums. Try this one for example:
    http://www.cafeconleche.org/books/xmljava/chapters/index.html

  • Parsing xml using DOM parser in java

    hi there!!!
    i don have much idea about parsing xml.. i have an xml file which consists of details regarding indentation and spacing standards of C lang.. i need to read the file using DOM parser in java n store each of the attributes n elements in some data structure in java..
    need help as soon as possible!!!

    DOM is the easiest way to parse XML document, google for JDOM example it is very easy to implement.
    you need to know what is attribute, what is text content and what is Value in XML then easily you can parse your document with dom (watch for space[text#] in your XML document when you parse it).
    you get root node then nodelist of childs for root then go further inside, it is easy believe me.

  • Parsing XML using java DOM

    hi
    i am trying to parse a document and change a specific text value within an element althouh when i run the program it changes the nodes text however when i check the xml file it doesnt show the changes it remains the same the code that i am using is as follow iwould be greatful if any one culd help:
    //  ReplaceText.java
    // Reads intro.xml and replaces a text node.
    // Java core packages
    import java.io.*;
    // Java extension packages
    import javax.xml.parsers.*;
    import javax.xml.parsers.*;
    import javax.xml.transform.*;
    import javax.xml.transform.stream.*;
    import javax.xml.transform.dom.*;
    // third-party libraries
    import org.xml.sax.*;
    import org.w3c.dom.*;
    public class ReplaceText {
       private Document document;
       public ReplaceText()
          // parse document, find/replace element, output result
          try {
             // obtain default parser
             DocumentBuilderFactory factory =
                DocumentBuilderFactory.newInstance();
             // set parser as validating          
             factory.setValidating( true );
             // obtain object that builds Documents
             DocumentBuilder builder = factory.newDocumentBuilder();
             // set error handler for validation errors
             builder.setErrorHandler( new MyErrorHandler() );
      System.err.println( "reading" );
             // obtain document object from XML document
             File f = new File("D:/Documents and Settings/Administrator/Desktop/xml adv java bk/appC/intro.xml");
              System.err.println( "reading" );
             document = builder.parse(f);
    //document = builder.parse( new File( "intro.xml" ) );
    System.err.println( "reading document" );
             // retrieve the root node
             Node root = document.getDocumentElement();
             if ( root.getNodeType() == Node.ELEMENT_NODE ) {
                Element myMessageNode = ( Element ) root;
                NodeList messageNodes =
                   myMessageNode.getElementsByTagName( "message5" );
                if ( messageNodes.getLength() != 0 ) {
                   Node message = messageNodes.item( 0 );
                        System.out.println("iiiii");
                   // create text node
                   Text newText = document.createTextNode(
                      "New Changed Message!!" );
                   // get old text node
                   Text oldText =
                      ( Text ) message.getChildNodes().item( 0 ); 
                   // replace text
                   //message.removeChild(oldText);
                   message.replaceChild( newText, oldText );
             // output Document object
             // create DOMSource for source XML document
             Source xmlSource = new DOMSource( document );
             // create StreamResult for transformation result
             Result result = new StreamResult( System.out );
             // create TransformerFactory
             TransformerFactory transformerFactory =
                TransformerFactory.newInstance();
             // create Transformer for transformation
             Transformer transformer =
                transformerFactory.newTransformer();
             transformer.setOutputProperty( OutputKeys.INDENT, "yes" );
               transformer.setOutputProperty( OutputKeys.STANDALONE, "yes" );
             // transform and deliver content to client
             transformer.transform( xmlSource, result );
          // handle exception creating DocumentBuilder
          catch ( ParserConfigurationException parserException ) {
             parserException.printStackTrace();
          // handle exception parsing Document
          catch ( SAXException saxException ) {
             saxException.printStackTrace();        
          // handle exception reading/writing data
          catch ( IOException ioException ) {
             ioException.printStackTrace();
             System.exit( 1 );
          // handle exception creating TransformerFactory
          catch (
             TransformerFactoryConfigurationError factoryError ) {
             System.err.println( "Error while creating " +
                "TransformerFactory" );
             factoryError.printStackTrace();
          // handle exception transforming document
          catch ( TransformerException transformerError ) {
             System.err.println( "Error transforming document" );
             transformerError.printStackTrace();
       public static void main( String args[] )
          ReplaceText replace = new ReplaceText();   
    }the xml file that i am using is as follows:
    <?xml version = "1.0"?>
    <!-- Fig. 28.10 : intro.xml             -->
    <!-- Simple introduction to XML markup   -->
    <!DOCTYPE myMessage [
         <!ELEMENT myMessage (message, message5)>
         <!ELEMENT message (#PCDATA)>
         <!ELEMENT message5 (#PCDATA)>
    ]>
    <myMessage>
         <message>welcome to the xml shhhhhushu</message>
         <message5>welcome to the xml shhhhhushu</message5>
    </myMessage>i would be greatful if some one could please help.....

    See if the Text 'oldText' actually has any text within it. Sometimes in DOM parsing, you will get something like:
    Element
       Text (blank)
       Text (actual)
       Text (blank)Whereas you would expect to receive:
    Element
       Text (actual)See if that is the case. If yes, modify your logic to iterate through the child text nodes until one with actual text inside of it (getNodeValue()) is found.
    - Saish

  • How to manipulate object mapping runtime using DOM parser in java?

    Scenario: We will be getting logical name of the table from which we have to fetch the details. We have few tables which have more or less same columns, the only difference is the prefix. Say we have Tables: Temp1 and Temp2 contains column as Temp1Col1 and Temp2Col1. I dont want to go with creating as many POJO classes in java as that of tables. So i will create only one POJO class with common attributes and at runtime i want to change the object mapping file of Hibernate to hold table values. I have an idea that this can be done using DOM parser. But it would be great if somebody can share the java code for the same.
    Thanks in advance.

    SAX is a parser, not a generator.Well,
    you can use it to create an XML file too. And it will take care of proper encoding, thus being much superior to a normal textwriter:
    See the following code snippet (out is a OutputStream):
    PrintWriter pw = new PrintWriter(out);
          StreamResult streamResult = new StreamResult(pw);
          SAXTransformerFactory tf = (SAXTransformerFactory) TransformerFactory.newInstance();
          //      SAX2.0 ContentHandler.
          TransformerHandler hd = tf.newTransformerHandler();
          Transformer serializer = hd.getTransformer();
          serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");//
          serializer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,"pdfBookmarks.xsd");
          serializer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,"http://schema.inplus.de/pdf/1.0");
          serializer.setOutputProperty(OutputKeys.METHOD,"xml");
          serializer.setOutputProperty(OutputKeys.INDENT, "yes");
          hd.setResult(streamResult);
          hd.startDocument();
          //Get a processing instruction
          hd.processingInstruction("xml-stylesheet","type=\"text/xsl\" href=\"mystyle.xsl\"");
          AttributesImpl atts = new AttributesImpl();
          atts.addAttribute("", "", "someattribute", "CDATA", "test");
          atts.addAttribute("", "", "moreattributes", "CDATA", "test2");
           hd.startElement("", "", "MyTag", atts);
    String curTitle = "Something inside a tag";
              hd.characters(curTitle.toCharArray(), 0, curTitle.length());
        hd.endElement("", "", "MyTag");
          hd.endDocument();
    You are responsible for proper nesting. SAX takes care of encoding.
    Hth
    ;-) stw

  • Sample java code which reads xml attributes using DOM Parser

    Hi Friends,
    I am looking for a sample java code which uses the DOM Parser to read the attributes values.
    My xml looks like below
    <?xml version='1.0' encoding='UTF-8'?>
    <root>
    <header unid="100" status="true">
    <validation stage="1" processed="10"/>
    </header>
    </root>
    Experts please help...
    Thanks in Advance
    JJ

    You have probably found lots of resources on the www for this by now, if not: [http://www.w3schools.com/dom/default.asp|http://www.w3schools.com/dom/default.asp]

  • DOM Parsing Not working in Applet.

    Hi,
    I ve an applet (parserapplet)which contains the DOM parsing. So xalan.jar(nearly 780 kb) required to assist the parsing. I gave archive="xalan.jar" in My html file. But the jar file is not downloaded from the archive tag. and ClassnotFoundException is thrown.
    the exact exception is:
    ======================
    com.ms.security.SecurityExceptionEx[Host]: cannot access file C:\WINNT\Java\lib\jaxp.properties
         at com/ms/security/permissions/FileIOPermission.check
         at com/ms/security/PolicyEngine.deepCheck
         at com/ms/security/PolicyEngine.checkPermission
         at com/ms/security/StandardSecurityManager.chk
         at com/ms/security/StandardSecurityManager.checkRead
         at java/io/File.exists
         at javax/xml/parsers/DocumentBuilderFactory.findFactory
         at javax/xml/parsers/DocumentBuilderFactory.newInstance
         at parserapplet.parseXMLMessage
         at parserapplet.init
         at com/ms/applet/AppletPanel.securedCall0
         at com/ms/applet/AppletPanel.securedCall
         at com/ms/applet/AppletPanel.processSentEvent
         at com/ms/applet/AppletPanel.processSentEvent
         at com/ms/applet/AppletPanel.run
         at java/lang/Thread.run
    javax.xml.parsers.FactoryConfigurationError: java.lang.ClassNotFoundException: org/apache/crimson/jaxp/DocumentBuilderFactoryImpl
         at javax/xml/parsers/DocumentBuilderFactory.newInstance
         at parserapplet.parseXMLMessage
         at parserapplet.init
         at com/ms/applet/AppletPanel.securedCall0
         at com/ms/applet/AppletPanel.securedCall
         at com/ms/applet/AppletPanel.processSentEvent
         at com/ms/applet/AppletPanel.processSentEvent
         at com/ms/applet/AppletPanel.run
         at java/lang/Thread.run
    I know signing the applet a bit. But though it is signed , second exception is constantly thrown. so please write in detail the procedure to sign the applet. and how to download xalan.jar in html page etc.,
    I require how to download the jar files, and after the completion of downloading of the jar files only, the applet should get executed. or shall i use different jar file(like crimson.jar?). This is urgent requirement.Please help me.!
    the classes for the parsing are not at all downloaded and hence the problem.
    help me reg that.
    thank you in advance/.
    Prasanna kumar k.

    Hello Prasanna kumar k.
    First you should sign your jar files (xerces.jar crimson.jar and xalan.jar) and recreate a cab files
    xerces.cab crimson.cab xalan.cab. To do that you should download sdk for java from microsoft .
    create testkey named testkey.pvk
    1. makecert -sv testkey.pvk -n "CN=your name" test.cer
    convert to public key
    2. cert2spc test.cer test.spc :
    create cab file
    3. cabarc -p -c -r -s 6144 test.cab
    sign the cab file
    4. signcode -j java.dll -jp -low -spc -v testkey.pvk -n test.cab
    after that you should use thia files in html:
    <!doctype html public "//W3//DID HTML 3.2 Final//EN">
    <HTML>
    <HEAD>
    <META content="text/html; charset=iso-8859-1">
    <TITLE>IBM Host On-Demand 6.0</TITLE>
    </HEAD>
    <BODY BACKGROUND="mankolpr/custom/img/Drawing1.gif">
    <CENTER>
    <IMG src="mankolpr/custom/img/images/ot_hod_log.gif">
    <P>
    <APPLET archive="crimson.jar,xerces.jar,xalan.jar" CODE="test.class" WIDTH=584 HEIGHT=450>
    <PARAM NAME=cabinets VALUE=crimson.cab,xerces.cab,xalan.cab>
    <PARAM NAME=background VALUE="pink">
    <p>If you are reading this message, your client platform is not capable of running
    IBM Host On-Demand. To run IBM Host On-Demand, you must have a Java-enabled web
    browser such as Netscape Navigator or Microsoft Internet Explorer.
    </APPLET>
    </CENTER>
    </BODY>
    </HTML>
    Best Regards,
    Tzur Emzari
    Project Manager
    Local Authority Data Processing Center LTD
    ISRAEL
    Tel : 972-4-8615754, Fax : 972-4-8661977
    Cell : 972-53-532448
    [email protected] <mailto:[email protected]>

  • Oracle XML DOM parser - attribute values are not printing on the screen ??

    Hi Everyone,
    I am just trying to use oracle DOM parser to paerse one of my xml file, java file can be compiled and run agianst a xml file, But I cannot see any attribute values printing on the screen..
    Appreciate if anyone can help, where I have gone wrong please?
    Below is the java file:
    // menna puthe DOMSample eka - duwanawa 19/12/2005
    import java.io.*;
    import java.net.*;
    import org.w3c.dom.*;
    import org.w3c.dom.Node;
    import oracle.xml.parser.v2.*;
    public class DOMSample {  //public class eka ***
    static public void main(String[] argv){  // main method eka ###
    try {
    if (argv.length != 1){
    // Must pass in the name of the XML file...
    System.err.println("Usage: java DOMSample filename");
    System.exit(1);
    // Get an instance of the parser
    DOMParser parser = new DOMParser();
    // Generate a URL from the filename.
    URL url = createURL(argv[0]);
    // Set various parser options: validation on,
    // warnings shown, error stream set to stderr.
    parser.setErrorStream(System.err);
    parser.showWarnings(true);
    // Parse the document.
    parser.parse(url);
    // Obtain the document.
    Document doc = parser.getDocument();
    // Print document elements
    System.out.print("The elements are: ");
    printElements(doc);
    // Print document element attributes
    System.out.println("The attributes of each element are: ");
    printElementAttributes(doc);
    catch (Exception e){
    System.out.println(e.toString());
    } // main method eka ###
    static void printElements(Document doc) {
    NodeList nl = doc.getElementsByTagName("*");
    Node n;
    for (int i=0; i<nl.getLength(); i++){
    n = nl.item(i);
    System.out.print(n.getNodeName() + " ");
    System.out.println();
    static void printElementAttributes(Document doc){
    NodeList nl = doc.getElementsByTagName("*");
    Element e;
    Node n;
    NamedNodeMap nnm;
    String attrname;
    String attrval;
    int i, len;
    len = nl.getLength();
    for (int j=0; j < len; j++){
    e = (Element)nl.item(j);
    System.out.println(e.getTagName() + ":");
    nnm = e.getAttributes();
    if (nnm != null){
    for (i=0; i<nnm.getLength(); i++){
    n = nnm.item(i);
    attrname = n.getNodeName();
    attrval = n.getNodeValue();
    System.out.print(" " + attrname + " = " + attrval);
    System.out.println();
    static URL createURL(String filename) {  // podi 3 Start
    URL url = null;
    try {
    url = new URL(filename);
    } catch (MalformedURLException ex) { /// BBBBBB
    try {
    File f = new File(filename);
    url = f.toURL();
    } catch (MalformedURLException e) {
    System.out.println("Cannot create URL for: " + filename);
    System.exit(0);
    } // BBBBBB
    return url;
    } // podi 3 End
    } //public class eka ***
    // End of program
    output comes as below:
    Isbn:
    Title:
    Price:
    Author:
    Message was edited by:
    chandanal

    Hi Chandanal,
    I edited your code slightly and I was able to get the correct output.
    I changed the following line:
    for (int j=0; j >< len; j++)to:
    for (int j=0; j < len; j++)I have included the complete source below:
    // menna puthe DOMSample eka - duwanawa 19/12/2005
    import java.io.*;
    import java.net.*;
    import org.w3c.dom.*;
    import org.w3c.dom.Node;
    import oracle.xml.parser.v2.*;
    public class DOMSample {
        //public class eka ***
        public static void main(String[] argv) {
            // main method eka ###
            try {
                if (argv.length != 1) {
                    // Must pass in the name of the XML file...
                    System.err.println("Usage: java DOMSample filename");
                    System.exit(1);
                // Get an instance of the parser
                DOMParser parser = new DOMParser();
                // Generate a URL from the filename.
                URL url = createURL(argv[0]);
                // Set various parser options: validation on,
                // warnings shown, error stream set to stderr.
                parser.setErrorStream(System.err);
                parser.showWarnings(true);
                // Parse the document.
                parser.parse(url);
                // Obtain the document.
                Document doc = parser.getDocument();
                // Print document elements
                System.out.print("The elements are: ");
                printElements(doc);
                // Print document element attributes
                System.out.println("The attributes of each element are: ");
                printElementAttributes(doc);
            } catch (Exception e) {
                System.out.println(e.toString());
        // main method eka ###
        static void printElements(Document doc) {
            NodeList nl = doc.getElementsByTagName("*");
            Node n;
            for (int i = 0; i < nl.getLength(); i++) {
                n = nl.item(i);
                System.out.print(n.getNodeName() + " ");
            System.out.println();
        static void printElementAttributes(Document doc) {
            NodeList nl = doc.getElementsByTagName("*");
            Element e;
            Node n;
            NamedNodeMap nnm;
            String attrname;
            String attrval;
            int i, len;
            len = nl.getLength();
            for (int j = 0; j < len; j++) {
                e = (Element)nl.item(j);
                System.out.println(e.getTagName() + ":");
                nnm = e.getAttributes();
                if (nnm != null) {
                    for (i = 0; i < nnm.getLength(); i++) {
                        n = nnm.item(i);
                        attrname = n.getNodeName();
                        attrval = n.getNodeValue();
                        System.out.print(" " + attrname + " = " + attrval);
                System.out.println();
        static URL createURL(String filename) {
            // podi 3 Start
            URL url = null;
            try {
                url = new URL(filename);
            } catch (MalformedURLException ex) {
                /// BBBBBB
                try {
                    File f = new File(filename);
                    url = f.toURL();
                } catch (MalformedURLException e) {
                    System.out.println("Cannot create URL for: " + filename);
                    System.exit(0);
            // BBBBBB
            return url;
        // podi 3 End
    } //public class eka ***-Blaise

  • DOM parsing In Applet (URgent)

    Is it possible to implement DOM parsing in Applet?
    I am getting classnotfoundException .
    I am giving the code below. pl read the code.
    Applet.(parserapplet.java)
    =========================
    import java.io.*;
    import java.awt.*;
    import java.net.*;
    import java.util.*;
    import java.applet.*;
    import com.security.*;
    // for DOM parsing ....
    import javax.xml.parsers.*;
    import org.xml.sax.*;
    import org.w3c.dom.Document;
    import org.w3c.dom.DOMException;
    public class parserapplet extends Applet
    public void init()
    public void start()
    try
    if (Class.forName("com.ms.security.PolicyEngine") != null)
    {  // required for IE
         PolicyEngine.assertPermission( PermissionID.SYSTEM );
    catch (Throwable cnfe)
         System.out.println("Policy Engine Exception: " + cnfe);
    try
         String str = "<?xml
    version=\"1.0\"?><html><body></body></html>";
         ByteArrayInputStream bis = new
    ByteArrayInputStream(str.getBytes());
         System.out.println("After creating input stream");
         BufferedInputStream bufIn     = new BufferedInputStream(new
    DataInputStream(bis));
         parseXMLMessage     (bufIn);
    catch(Exception e){}
    // Actual DOM parsing goes here.....
    public void parseXMLMessage(InputStream xmlMessage)
    Document document      = null;
         DocumentBuilder documentBuilder           = null;
         DocumentBuilderFactory documentBuilderFactory     = null;
         try
         documentBuilderFactory = DocumentBuilderFactory.newInstance();
         documentBuilder     = documentBuilderFactory.newDocumentBuilder();
         document     = documentBuilder.parse(xmlMessage);
         System.out.println("Document node: " + document);
         catch(FactoryConfigurationError fce)
         System.out.println("Exception Factory configuration error " + fce);
         catch(ParserConfigurationException pce)
         System.out.println("Exception Parser configuration Exception " pce);
         catch(SAXException saxe)
         System.out.println("Exception SAX error " + saxe);
         catch(Exception e)
         System.out.println("Exception " + e);
    Html code:
    =========
    <html>
    <body>
    <APPLET code="parserapplet.class" archive = "xalan.jar" width=0
    height=0
    MAYSCRIPT>
    <param name=cabbase value=MyApplet.cab>
    </APPLET>
    </body>
    </html>
    I have signed the Applet using signcode utility and i have put the
    parserapplet.class in the MyApplet cab file and signed it. On invoking
    the html file, it request for permission, and after clicking yes, the
    applet loads.Fine.
    No problem upto this stage.
    But after loading of the applet the following exception is thrown in
    Javaconsole.
    Exception:
    =========
    com.ms.security.SecurityExceptionEx[Host]: cannot access file
    C:\WINNT\Java\lib\jaxp.properties
    at com/ms/security/permissions/FileIOPermission.check
    at com/ms/security/PolicyEngine.deepCheck
    at com/ms/security/PolicyEngine.checkPermission
    at com/ms/security/StandardSecurityManager.chk
    at com/ms/security/StandardSecurityManager.checkRead
    at java/io/File.exists
    at javax/xml/parsers/DocumentBuilderFactory.findFactory
    at javax/xml/parsers/DocumentBuilderFactory.newInstance
    at parserapplet.parseXMLMessage
    at parserapplet.init
    at com/ms/applet/AppletPanel.securedCall0
    at com/ms/applet/AppletPanel.securedCall
    at com/ms/applet/AppletPanel.processSentEvent
    at com/ms/applet/AppletPanel.processSentEvent
    at com/ms/applet/AppletPanel.run
    at java/lang/Thread.run
    javax.xml.parsers.FactoryConfigurationError:
    java.lang.ClassNotFoundException:
    org/apache/crimson/jaxp/DocumentBuilderFactoryImpl
    at javax/xml/parsers/DocumentBuilderFactory.newInstance
    at parserapplet.parseXMLMessage
    at parserapplet.init
    at com/ms/applet/AppletPanel.securedCall0
    at com/ms/applet/AppletPanel.securedCall
    at com/ms/applet/AppletPanel.processSentEvent
    at com/ms/applet/AppletPanel.processSentEvent
    at com/ms/applet/AppletPanel.run
    at java/lang/Thread.run
    I dont know which .jar file to archive (i tried xalan,crimson, jaxp
    but which of no use). I was surprised why the security Exception is
    thrown , when parsing.
    I have not accessed the System files!( but it searches for
    jaxp.properties file!). I think the jar file is not downloaded. How to
    verify that it is downloaded in applet?
    The above code is only for sample.
    If anybody who knows how to correct it please mail me at:
    "[email protected]" with corrected code. I want this very
    urgently.
    Help meeeeeeeeeeeeeeeeeeee!!!!!
    Prasanna.

    Have you found the answer to this problem? I am having a similar problem when running the parser in an ActiveX Bean.
    THanks

  • Problem in parsing a xml string using dom parser

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

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

  • 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.

  • JmsAdapter DOM Parsing Exception handling

    Hi,
    I'm currently facing a problem with the behaviour of the Jms Adapter.
    Whenever a JMS message is put in the queue and that message is not XML valid, the Jms Adapter (consumer) throw the exception "DOM Parsing Exception in translator Exception".
    That's fine, I understand that the message was not well formed. But what is not fine is that the underlying BPEL is not instanciated : meaning I can't handle the exception properly.
    Is there a way to force the Jms Adapter not to crash on the DOM Parsing for the BPEL to be instanciated (and then being able to handle the exception there) ?
    Or is there a way to handle the error thrown by the Jms Adapter itself ? How ?
    I think I do have a workaround to this if there is no better option (if both above questions cannot be answered) but I would rather not implement it since it will involve some extra steps / complexity.
    > It would be to check the "native format opaque schema" option and then use a java embedded to decode the base64 into a string for eventually parsing it.
    regards,
    mathieu

    Hi Mathieu,
    The messages that error out before being posted to the service infrastructure are referred to as rejected messages. For example, the Oracle File Adapter selects a file having data in CSV format and tries to translate it to XML format (using NXSD). If there is any error in the translation, this message is rejected and are not be posted to the target composite.
    You can create rejection handlers to handle message errors. Message errors include those that occur during translation, correlation ID mismatch and XML parsing after message reception.
    Docs on how to do that are here...
    http://docs.oracle.com/cd/E28280_01/integration.1111/e10231/life_cycle.htm#CIAIICJJ
    Cheers,
    Vlad

Maybe you are looking for

  • How do I export full conversations in apple mail

    Sometimes conversations in Mail provide a quick diary of business and personal events.  Is there anyway to export a bunch of emails, all at once, into a pdf or text file?

  • Which one is fast?

    public class Point2D {     private int x, y;     public Point2D() { x = 0; y = 0; }     //public Point2D() { this(0,0); }     public Point2D(int x, int y) {this.x = x; this.y = y;}     public int getX() {return x;}     public int getY() {return y;}  

  • Static sounds on my laptop

    I hear static sounds when i play music on my laptop (mp3) or watch video on my laptop (mp4) or on youtube online.  I first noticed it a long time ago and it was sporadic. but now it is continues for 3 days.  I hear it when i have my headset plugged i

  • Is there a file size limit for images in keynote on a mac?

    Is there a file size limit for images in keynote on a mac?

  • Automatic Load html page in div.

    Sir, I want to display html page in a div automatically when the main page load which contain div. Rajeev.