Parsing an xml file using xerces DOM  parser

Hi
I want to parse a simple xml file using DOM parser.
The file is
<Item>
     <SubItem>
          <title>SubItem0</title>
          <attr1>0</attr1>
          <attr2>0</attr2>
          <attr3>0</attr3>
     </SubItem>
     <SubItem>
          <title>SubItem1</title>
          <attr1>1</attr1>
          <attr2>0</attr2>
          <attr3>0</attr3>
     </SubItem>
     <SubItem>
          <title>SubItem2</title>
          <attr1>1</attr1>
          <attr2>1</attr2>
          <attr3>0</attr3>
          <SubItem>
               <title>SubItem20</title>
               <attr1>2</attr1>
               <attr2>1</attr2>
               <attr3>0</attr3>
          </SubItem>
          <SubItem>
               <title>SubItem21</title>
               <attr1>1</attr1>
               <attr2>1</attr2>
               <attr3>0</attr3>
          </SubItem>
     </SubItem>
</Item>
I just want to parse this file and want to store the values in desired datastructures,
I am trying using DOM parser, since it gives a tree structure, which is ok in this case.
public void init()
          InputReader ir     =new InputReader("Habsys");
          Document      doc     =ir.read("Habitat");
          System.out.println(doc);
          traverse(doc);
private void traverse(Document idoc)
          NodeList lchildren=idoc.getElementsByTagName("SubItem");
          for(int i=0;i<lchildren.getLength();i++)
               String lgstr=lchildren.item(i).getNodeName();
               if(lgstr.equals("SubItem"))
                    traverse(lchildren.item(i));
private void traverse (Node node) {
int type = node.getNodeType();
if (type == Node.ELEMENT_NODE)
System.out.println ("Name :"+node.getNodeName());
if(!node.hasChildNodes())
System.out.println ("Value :"+node.getNodeValue());
NodeList children = node.getChildNodes();
if (children != null) {
for (int i=0; i< children.getLength(); i++)
traverse (children.item(i));
But I am not getting required results, a lot of values I am getting as null
Could anybody tell me how to retrieve the data from the xml file, I simply want to read data and store it in data structures. For eg, for tag Subitem with title as ' SubItem1' has attr1 as '1', attr2 as'0' and attr3 as '0'.
Thanks
Gaurav

Check This Sample Code....
public void amethod(){
DocumentBuilderFactory dbf = null;
DocumentBuilder docBuilder = null;
Document doc = null;
try{
     dbf = DocumentBuilderFactory.newInstance();
     db = dbf.newDocumentBuilder();
     doc = db.parse(New File("path/to/your/file"));
     Node root = doc.getDocumentElement();
     System.out.println("Root Node = " + root.getNodeName());
     readNode(root);
}catch(FactoryConfigurationError fce){ fce.printStackTrace();
}catch(ParserConfigurationException pce){  pce.printStackTrace();
}catch(IOException ioe){  ioe.printStackTrace();
}catch(SAXException saxe){  saxe.printStackTrace();
private void readNode(Node node) {
System.out.println("Current Node = " + node.getNodeName());
readAttributes(node);
readChildren(node);
private void readAttributes(Node node) {
if (!node.hasAttributes())
     return;
System.out.println("Attributes:");
NamedNodeMap attrNodes = node.getAttributes();
for (int i=0; i<attrNodes.getLength(); i++) {
Attr attr = (Attr)attrNodes.item(i);
System.out.println(attr.getNodeName() + " => " + attr.getNodeValue());
private void readChildren(Node node) {
if (!node.hasChildNodes())
     return;
System.out.println("Value/s:");
NodeList childNodes = node.getChildNodes();
for (int i=0; i<childNodes.getLength(); i++) {
Node child = (Node)childNodes.item(i);
if (child.getNodeType() == Node.ELEMENT_NODE) {
readNode(child);
continue;
if (child.getNodeType() == Node.TEXT_NODE) {
if (child.getNodeValue()!=null)
System.out.println(child.getNodeValue());

Similar Messages

  • Changing /updating an xml file using JAXP(DOM)

    Hello,
    i am fairly new to xml and am using it in my degree project.I am able to retrieve and read data from a fairly large xml file using JAXP(DOM) and/or XMLBeans.I am having difficulties in updating the xml document. Any updation i believe is ito be saved into a new xml document,but dont know how to proceed with it. Any help would be appreciated.
    Following is a snippet of my code using JAXP. Here i am able to retrieve data from the source file.
    File document=new File("C:\\tester.xml");
    try {
    DocumentBuilderFactory factory
    = DocumentBuilderFactory.newInstance();
    DocumentBuilder parserr = factory.newDocumentBuilder();
    Document doc=parserr.parse(document);
    System.out.println(document + " is well-formed.");
    NodeList n2=doc.getElementsByTagName("Top");
    NodeList n3=doc.getElementsByTagName("Base");
    int x=n2.getLength();
    System.out.println("There are " x "players");
    for(int g=0;g<=x;g++)
    System.out.println("Top is" + n2.item(g).getFirstChild().getNodeValue()+" Base is" +n3.item(g).getFirstChild().getNodeValue());
    --------------------------------------------------------------------------------

    Following is my updation code to the dom tree:
    NodeList list=doc.getElementsByTagName("Information");
    for(int i=0; i<list.getLength();i++){
    Node thissampnode=list.item(i);
    Node thisNameNode=thissampnode.getFirstChild();
    if(thisNameNode==null) continue;
    if(thisNameNode.getFirstChild()==null)continue;
    // if(thisNameNode.getFirstChild() !(instanceof org.w3c.dom.Text) continue;
    String data=thisNameNode.getFirstChild().getNodeValue();
    if (! data.equals("0.59")) continue;
    Node newsampNode = doc.createElement("Samp");
    Node newsampTopNode = doc.createElement("Top");
    Text tnNode = doc.createTextNode("0.50");
    newsampTopNode.appendChild(tnNode);
    Element newsampRef = doc.createElement("Ref");
    Text tsr = doc.createTextNode("0");
    newsampRef.appendChild(tsr);
    Element newsampType = doc.createElement("Type");
    Text tt = doc.createTextNode("z");
    newsampType.appendChild(tt);
    Element newsampbase = doc.createElement("Base");
    Text sb = doc.createTextNode("0.55");
    newsampbase.appendChild(sb);
    newsampNode.appendChild(newsampTopNode);
    newsampNode.appendChild(newsampRef);
    newsampNode.appendChild(newsampType);
    newsampNode.appendChild(newsampbase);
    rootNode.insertBefore(newsampNode, thissampnode);
    Here i dont see any changes to the original xml source file.

  • Updating XML file using DOM parser

    Hi,
    Can someone help me, how to update following XML file using DOM parser.
    The following is my XML file.
    <students>
         <student>
              <id>1</id>
              <name>abc</name>
         </student>
         <student>
              <id>2</id>
              <name>xyz</name>
         </student>
         <student>
              <id>3</id>
              <name/>
         </student>
         <student>
              <id>4</id>
              <name>ijk</name>
         </student>
         <student>
              <id>5</id>
              <name></name>
         </student>
    </students>Consider, I will input 2 fields, ie., id & name. For the matching Id, the name has to be updated.
    Though, I have achieved this, but I am unable to update the value for 3rd record, & 5th record ie., id=3 & id=5. Since, these are blank.
    Thanks.

    Some <name> elements have a child node which is a text node. From what you say it appears you know how to change those text nodes.
    The other <name> elements don't have any child nodes. But you want one. This suggests to me that you need code that creates a text node and adds it to the <name> element as its child.

  • XML validation using XDK DOM/SAX Parser

    Hello,
    I am trying to validate xml against xsd using SAX/DOM parser, both the files are stored as CLOB column in the database. I have the requirement to report all the validation errors and based on some helpful advice/code from the earlier posts in this forum, I have used the following code to validate and report the errors.
    The code works fine but for large files it never goes beyond a certain number of errors i.e. getNumMessages() (XMLParseException) never returns value greater than 100 and thus limits the output of the validation errors. Any pointers to suggest change in code or an alternative will be extremely helpful.
    Datebase Version : Oracle Database 11g Enterprise Edition Release 11.2.0.2.0 - 64bit Production
    CREATE OR REPLACE AND RESOLVE JAVA SOURCE NAMED as package <package name>;
    import java.net.*;
    import java.io.*;
    import java.util.*;
    import java.sql.SQLException;
    import oracle.sql.CLOB;
    import oracle.xml.parser.schema.*;
    import oracle.xml.parser.v2.*;
    import org.w3c.dom.*;
    public class XMLSchemaVal
    public static String validate(CLOB xmlDoc, CLOB xsdDoc)
    throws Exception
    //Build Schema Object
    XSDBuilder builder = new XSDBuilder();
    Reader xsdInUnicodeFormat = xsdDoc.getCharacterStream();
    XMLSchema schemadoc = (XMLSchema)builder.build(xsdInUnicodeFormat, null);
    //Build XML Object
    Reader xmlInUnicodeFormat = xmlDoc.getCharacterStream();
    // Genereate the SAX
    SAXParser saxparser_doc = new SAXParser();
    // Set Schema Object for Validation
    saxparser_doc.setXMLSchema(schemadoc);
    saxparser_doc.setValidationMode(XMLParser.SCHEMA_VALIDATION);
    saxparser_doc.setPreserveWhitespace (true);
    String returnValue;
    try {
    saxparser_doc.parse (xmlInUnicodeFormat);
    returnValue = "The input XML parsed without errors.\n";
    catch (XMLParseException se) {
    returnValue = "Parser Exception: ";
    for (int i=0 ; i < se.getNumMessages(); i++)
    returnValue += "<LN: " + se.getLineNumber(i) + ">: " + se.getMessage(i);
    //returnValue = "Parser Exception: " + se.getNumMessages();
    catch (Exception e) {
    returnValue = "NonParserException: " + e.getMessage();
    return returnValue;
    Function to call the above utility from PL/SQL
    CREATE OR REPLACE FUNCTION F_XMLSCHEMAVALIDATION (P_XML IN clob ,P_XSD IN clob) RETURN VARCHAR2 IS
    LANGUAGE JAVA NAME XMLSchemaVal.validate(oracle.sql.CLOB,oracle.sql.CLOB) return java.lang.String';
    Thanks.

    I have the same question. I have an external DTD. I wish to parse an xml file using XMLParser.xmlparse. If I first call XMLParser.xmlparseDTD and then call xmlparse with the XML_FLAG_VALIDATE will the xml automatically be validated against the previously parsed DTD? There is no DOCTYPE declaration in the xml file.
    The demo code on OTN for Java is great but has no relation to the code you would use in C++ (no set functions in C++).

  • SAX: How to create new XML file using SAX parser

    Hi,
    Please anybody help me to create a XML file using the Packages in the 5.0 pack of java. I have successfully created it reading the tag names and values from database using DOM but can i do this using SAX.
    I am successful to read XML using SAX, now i want to create new XML file for some tags and its values using SAX.
    How can i do this ?
    Sachin Kulkarni

    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

  • Cannot close an XML file used for parsing

    Hi All,
    I appears to have difficulty closing (possibly flushing it first) an XML file that was subsequently being parsed without success. The error generated is:
    org.jdom.input.JDOMParseException: Error on line 23: The element type "form" must be terminated by the matching end-tag "</form>".
    Below is the code snippets of readData() to retrieve (HTML) data from a website, save it to a file, then convert to XML format before returning the new filename:
    public String readData() {
        try {
              URL url  = new URL("http://www.abc.com");
              URLConnection connection = url.openConnection();      
              InputStream isInHtml = url.openStream();   // throws an IOException    
              disInHtml = new DataInputStream(new BufferedInputStream(isInHtml));         
              System.out.flush();
              FileOutputStream fosOutHtml = null;
              fosOutHtml = new FileOutputStream("C:\\Temp\\ABC.html");
              int oneChar, count=0;
              while ((oneChar=disInHtml.read()) != -1)
                  fosOutHtml.write(oneChar);
              isInHtml.close();
              disInHtml.close();
              fosOutHtml.flush();    // optional
              fosOutHtml.close();
        try {
              File fileInHtml = new File("C:\\Temp\\ABC.html");
              FileReader frInHtml = new FileReader(fileInHtml);
              BufferedReader brInHtml = new BufferedReader(frInHtml);
              String string = "";
              while (brInHtml.ready())
                  string += brInHtml.readLine() + "\n";
              fwOutXml  = new FileWriter("C:\\Temp\\ABC.xml");
              pwOutXml  = new PrintWriter(fwOutXml);
              light_html2xml html2xml = new light_html2xml();
              pwOutXml.print(html2xml.Html2Xml(string));
              system.out.flush()     // optional
              fwOutXml.flush();      // optional
              fwOutXml.close();
              pwOutXml.flush();      // optional
              pwOutXml.close();
              return fileInHtml.getAbsolutePath();
    // parseData reads the XML file using the name returned by readData()
    public void parseData(String XMLFilename)
        try
            FileReader frInXml = new FileReader(FileName);
            BufferedReader brInXml = new BufferedReader(frInXml);
            SAXBuilder saxBuilder = new SAXBuilder("org.apache.xerces.parsers.SAXParser"); // JDOMParseException generated.
    }These codes would worked when they were in a single method but I have since placed some structure around them using a number methods.
    This issue has risen in th past where I have been able to close the XML file prior to reading them again. However, I don't have a solution for it this time round.
    I am running JDK 1.6.0_10, Netbeans 6.1, JDOM 1.1 on Windows XP platform.
    Any assistance would be appreciated.
    Many thanks,
    Jack

    Hi Alain,
    I have added the additional I/O statements in the finally clause as follows but the problem still persisted:
    readData()
    // reading data (html) from the webpage and save it in html format.
    try {
    catch { …. }
    finally {
           System.out.flush();
           isInHtml.close();
           disInHtml.close();
           fosOutHtml.flush();
           fosOutHtml.getFD().sync();
           fosOutHtml.close();
    // convert the html webpage format to xml format
    try {
    catch { …. }
    finally {
           System.out.flush();
           fwOutXml.flush();
           fwOutXml.close();
           pwOutXml.flush();
           pwOutXml.close();
    Below is a short listing of the new XML file:
      <?xml version="1.0" encoding="iso-8859-1" ?>
    - <html>
    - <head>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
      <meta name="keywords" content="California, cities, towns, villages, list, zipcodes, postal codes, united states, ca" />
      <meta name="description" content="Cities, towns and suburbs in California, United States (CA) starting with A" />
      <title>Cities and Towns in California starting with A – ABC Company</title>
      <link rel="stylesheet" href="http://www.abc.com/style.css" type="text/css" media="screen" />
      </head>
    - <body>
      <a name="top" />
    - <div id="container">
    - <div id="header">
      <div id="postmark" />
    - <a href="http://www.abc.com/" class="imglink">
      <img id="logoimg" src="http://www.abc.com/images/zipcodes.gif" width="192" height="33" alt="Zipcodes America Logo" />
      </a>
      <hr />
      </div>
    - <div id="nav">
    - <ul>
    - <li>
      <a href="http://www.abc.com/" title="Home Page">Home</a>
      </li>
    - <li>
      <strong>Search</strong>
      (zipcode or suburb)
    - <div class="hide">
      <form method="post" action="http://www.abc.com/search" />        // line 23
      </div>
      <input type="text" name="q" class="searchbox" alt="Search query" />
      <br />
      <input type="submit" value="find!" class="searchbutton" alt="Perform search" />
      <div class="hide" />
      </li>
    …What I find it interesting is that it is possible to parse the above XML file with the same parseData() from another class without any problem. As a result, I have come to the following conclusion so far:
    ( i ) There is some file locking that is prevent saxBuilder from parsing the XML file at the time.
    ( ii ) The light_html2xml does not appears to have correctly converted over the orginal Html to Xml but some how it has been picked up by the parser in the same class, but not by the same parser from another class.
    ( iii ) I would like to use another conversion tool such as Tagsoup in place of light_html2xml to determine where the cause of this issue is coming from. As a result, would you or anyone be able to assist me coming up with a few lines of conversion statements using Tagsoup since I am not familiar with using this tool?
    ( iv ) light_html2xml is good as it strip out all namespace, DTD, Entity Resolver, etc and only return what I need. JTidy does correct conversion but include namespace, DTD, Entity Resolver which makes parsing difficulty.
    Many thanks again,
    Jack

  • Parsing a XML file using Jdom-Problem.

    Hi all,
    I am reposting it as I was told to format the code and send it again.
    I am trying to parse a xml file using a jdom java code.This code works fine if I remove xmlns attribute in the root element. (I get the expected result) .If the "xmlns" attribute is put in the xml as it should be then the parsing and retrieving returns null. Please tell me how to fix this issue.
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Xml
    <process name="CreateKBEntryService" targetNamespace="http://serena.com/CreateKBEntryService" suppressJoinFailure="yes" xmlns:tns="http://serena.com/CreateKBEntryService" xmlns="http://schemas.xmlsoap.org/ws/2003/03/business-process/" xmlns:bpelx="http://schemas.oracle.com/bpel/extension" xmlns:ora="http://schemas.oracle.com/xpath/extension" xmlns:nsxml0="http://localhost:8080/axis/services/CreateKBEntryService" xmlns:nsxml1="http://DefaultNamespace" xmlns:bpws="http://schemas.xmlsoap.org/ws/2003/03/business-process/">
    <partnerLinks>
    <partnerLink name="client" partnerLinkType="tns:CreateKBEntryService" myRole="CreateKBEntryServiceProvider"/>
    <partnerLink name="CreateKBEntryPartnerLink" partnerLinkType="nsxml0:CreateKBEntryLink" partnerRole="CreateKBEntryProvider"/>
    </partnerLinks>
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~`
    Java:
    import java.io.*;
    import java.util.*;
    import org.jdom.Document;
    import org.jdom.Element;
    import org.jdom.input.SAXBuilder;
    public class sample1 {
    public static void main(String[] args) throws Exception {
    // create a XML parser and read the XML file
    SAXBuilder oBuilder = new SAXBuilder();
    Document oDoc = oBuilder.build(new File("**xml file location**"));
    Element root = oDoc.getRootElement();
    System.out.println(root.getName());
    String tgtns= root.getAttributeValue("targetNamespace");
    System.out.println("tgt ns "+ tgtns);
    List list= root.getChildren("partnerLinks");
    Iterator it1= list.iterator();
    System.out.println("Iterator 1 - "+list.size());
    while(it1.hasNext()){
    Element partnerlinks = (Element)it1.next();
    List list2= partnerlinks.getChildren("partnerLink");
    System.out.println("iterator 2 - "+list2.size());
    }~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Result:
    Without Xmlns in xml file(Expected and correct output)
    process
    tgt ns http://serena.com/CreateKBEntryService
    Iterator 1 - 1//expected and correct result that comes when I remove xmlns attribute from xml
    iterator 2 - 2
    Result with xmlns:
    process
    tgt ns http://serena.com/CreateKBEntryService
    Iterator 1 - 0 //instead of 0 should return 1

    LOL
    This is what you get for working 12 hours straight....
    I changed:
    xmlObject["mydoc"]["modelglue"]["event-handlers"]["event-handler"][i].xmlAttrib utes["name"]<br>
    to:
    #mydoc["modelglue"]["event-handlers"]["event-handler"][i].xmlAttrib utes["name"]#<br>
    xmlObject is the name of my xml object in memory, and then you reference from the root of the xml doc down the chain.
    Sorry for the inconvenience,
    Rich

  • Problem writing xml file using DOM

    Hi,
    I am trying to write a xml file using DOM. I am using xalan 2.5, xerces 1.4.4, jdk 1.3.1 in JRun 3 on windows.
    The code where I get exception :
                   TransformerFactory tFactory = TransformerFactory.newInstance();
                   Transformer transformer = tFactory.newTransformer();
                   transformer.transform(new DOMSource(doc), new StreamResult("pr.xml"));
    I get the runtime error as follows:
    javax.servlet.ServletException: null
    java.lang.NoSuchMethodError
         at org.apache.xml.utils.DOM2Helper.getNamespaceOfNodeDOM2Helper.java:342)
         at org.apache.xml.utils.TreeWalker.startNode(TreeWalker.java:387)
         at org.apache.xml.utils.TreeWalker.traverse(TreeWalker.java:202)
         at org.apache.xalan.transformer.TransformerIdentityImpl.transform(TransformerIdentityImpl.java:343)
    Thinking it is because of classpath, I placed xalan 2.5, xerces 1.4.4 jar files in jrun admin lib directory and in server lib directory as well. Still getting the same error.
    Any suggestion?
    Thanks in advance

    xalan is included in JRun 4. However JRun 3 does not.
    However I tried with the same code in JRun3 in different system. The error is completely different. I understand this is because of different version of files. trying to solve ;)
    Here my new exception
    javax.servlet.ServletException: org/w3c/dom/ranges/DocumentRange
    java.lang.NoClassDefFoundError: org/w3c/dom/ranges/DocumentRange
         at java.lang.ClassLoader.defineClass0(Native Method)
         at java.lang.ClassLoader.defineClass(ClassLoader.java:493)
         at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:111)
         at java.net.URLClassLoader.defineClass(URLClassLoader.java:248)
         at java.net.URLClassLoader.access$100(URLClassLoader.java:56)
         at java.net.URLClassLoader$1.run(URLClassLoader.java:195)
         at java.security.AccessController.doPrivileged(Native Method)
         at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
         at java.lang.ClassLoader.loadClass(ClassLoader.java:299)
         at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:286)
         at java.lang.ClassLoader.loadClass(ClassLoader.java:255)
         at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:315)
         at java.lang.ClassLoader.defineClass0(Native Method)
         at java.lang.ClassLoader.defineClass(ClassLoader.java:493)
         at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:111)
         at java.net.URLClassLoader.defineClass(URLClassLoader.java:248)
         at java.net.URLClassLoader.access$100(URLClassLoader.java:56)
         at java.net.URLClassLoader$1.run(URLClassLoader.java:195)
         at java.security.AccessController.doPrivileged(Native Method)
         at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
         at java.lang.ClassLoader.loadClass(ClassLoader.java:299)
         at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:286)
         at java.lang.ClassLoader.loadClass(ClassLoader.java:255)
         at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:315)
         at org.apache.xerces.jaxp.DocumentBuilderImpl.(Unknown Source)
         at org.apache.xerces.jaxp.DocumentBuilderFactoryImpl.newDocumentBuilder(Unknown Source)
         at com.cybell.appl.deliveryorder.cmd.CreateXMLDOFile.createFile(CreateXMLDOFile.java:73)
         at com.cybell.appl.deliveryorder.cmd.CreateXMLDOFile.execute(CreateXMLDOFile.java:36)
         at com.cybell.appl.framework.cmd.BaseCommand.start(BaseCommand.java:50)
         at com.cybell.appl.framework.control.BaseController.service(BaseController.java:38)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:865)
         at allaire.jrun.servlet.JRunSE.service(../servlet/JRunSE.java:1013)
         at allaire.jrun.servlet.JRunSE.runServlet(../servlet/JRunSE.java:925)
         at allaire.jrun.servlet.JRunNamedDispatcher.forward(../servlet/JRunNamedDispatcher.java:34)
         at allaire.jrun.servlet.Invoker.service(../servlet/Invoker.java:84)
         at allaire.jrun.servlet.JRunSE.service(../servlet/JRunSE.java:1013)
         at allaire.jrun.servlet.JRunSE.runServlet(../servlet/JRunSE.java:925)
         at allaire.jrun.servlet.JRunRequestDispatcher.forward(../servlet/JRunRequestDispatcher.java:88)
         at allaire.jrun.servlet.JRunSE.service(../servlet/JRunSE.java:1131)
         at allaire.jrun.servlet.JvmContext.dispatch(../servlet/JvmContext.java:330)
         at allaire.jrun.http.WebEndpoint.run(../http/WebEndpoint.java:107)
         at allaire.jrun.ThreadPool.run(../ThreadPool.java:272)
         at allaire.jrun.WorkerThread.run(../WorkerThread.java:75)

  • How to retrieve data (xml file) using jsp

    I am a newbie to xml. I have decided to store my information in the xml file. may I know how can I retrieve my information from the xml file?
    Thanx in advance.

    I am a newbie to xml. I have decided to store my
    information in the xml file. may I know how can I
    retrieve my information from the xml file?
    Thanx in advance.You can get the information from the XML file using one of the parsers available, such as Xerces http://xml.apache.org, and JDOM as an API.
    Using this you have the option of having a SAXParser or a DOMParser.
    SAX (Simple API for XML) is an event based parser, so if you know the XML structure, and need to find a certain element, you can just look for the element name,and retrieve the value of the element, it's attributes and its children.
    DOM(Document Object Model)represents the XML as a tree, but uses more resources as it stores the entire tree in memory. But it is good in that you can traverse the whole tree.
    JDOM would be a good idea too. If you download this, you can use it's API, which is very good, that will use the parser on your system (Xerces). I would definately recommend JDOM.

  • How to create new XML file using retreived XML content by using SAX API?

    hi all,
    * How to create new XML file using retreived XML content by using SAX ?
    * I have tried my level best, but output is coming invalid format, my code is follows,
    XMLFileParser.java class :-
    import java.io.StringReader;
    import java.io.StringWriter;
    import javax.xml.transform.OutputKeys;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerConfigurationException;
    import javax.xml.transform.TransformerException;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.dom.DOMResult;
    import javax.xml.transform.sax.SAXSource;
    import javax.xml.transform.sax.SAXTransformerFactory;
    import javax.xml.transform.sax.TransformerHandler;
    import javax.xml.transform.stream.StreamResult;
    import org.w3c.dom.Document;
    import org.xml.sax.Attributes;
    import org.xml.sax.InputSource;
    import org.xml.sax.SAXException;
    import org.xml.sax.helpers.XMLFilterImpl;
    public class PdfParser extends XMLFilterImpl {
        private TransformerHandler handler;
        Document meta_data;
        private StringWriter meta_data_text = new StringWriter();
        public void startDocument() throws SAXException {
        void startValidation() throws SAXException {
            StreamResult streamResult = new StreamResult(meta_data_text);
            SAXTransformerFactory factory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
            try
                handler = factory.newTransformerHandler();
                Transformer transformer = handler.getTransformer();
                transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
                transformer.setOutputProperty(OutputKeys.INDENT, "yes");
                handler.setResult(streamResult);
                handler.startDocument();
            catch (TransformerConfigurationException tce)
                System.out.println("Error during the parse :"+ tce.getMessageAndLocation());
            super.startDocument();
        public void startElement(String namespaceURI, String localName,
                String qualifiedName, Attributes atts) throws SAXException {
            handler.startElement(namespaceURI, localName, qualifiedName, atts);
            super.startElement(namespaceURI, localName, qualifiedName, atts);
        public void characters(char[] text, int start, int length)
                throws SAXException {
            handler.characters(text, start, length);
            super.characters(text, start, length);
        public void endElement(String namespaceURI, String localName,
                String qualifiedName) throws SAXException {
            super.endElement("", localName, qualifiedName);
            handler.endElement("", localName, qualifiedName);
        public void endDocument() throws SAXException {
        void endValidation() throws SAXException {
            handler.endDocument();
            try {
                TransformerFactory transfactory = TransformerFactory.newInstance();
                Transformer trans = transfactory.newTransformer();
                SAXSource sax_source = new SAXSource(new InputSource(new StringReader(meta_data_text.toString())));
                DOMResult dom_result = new DOMResult();
                trans.transform(sax_source, dom_result);
                meta_data = (Document) dom_result.getNode();
                System.out.println(meta_data_text);
            catch (TransformerConfigurationException tce) {
                System.out.println("Error occurs during the parse :"+ tce.getMessageAndLocation());
            catch (TransformerException te) {
                System.out.println("Error in result transformation :"+ te.getMessageAndLocation());
    } CreateXMLFile.java class :-
    Sax.startDocument();
    Sax.startValidation();
    Sax.startElement("", "pdf", "pdf", new AttributesImpl());
    Sax.startElement("", "basic-metadata", "basic-metadata", new AttributesImpl());          
    String xmp_str = new String(meta_data.getByteArray(),"UTF8");
    char[] xmp_arr = xmp_str.toCharArray();
    Sax.characters(xmp_arr, 0, xmp_arr.length);
    Sax.endElement("", "pdf", "pdf");
    Sax.endValidation();
    Sax.endDocument();
    Sax.endElement("", "basic-metadata", "basic-metadata");* In CreateXMLFile.java
    class, I have retreived the xml content in the meta_data object, after that i have converted into character array and this will be sends to SAX
    * In this case , the XML file created successfully but the retreived XML content added as an text in between basic-metadata Element, that is, retreived XML content
    is not an XML type text, it just an Normal text Why that ?
    * Please help me what is the problem in my code?
    Cheers,
    JavaImran

    Sax.startDocument();
    Sax.startValidation();
    Sax.startElement("", "pdf", "pdf", new AttributesImpl());
    Sax.startElement("", "basic-metadata", "basic-metadata", new AttributesImpl());          
    String xmp_str = new String(meta_data.getByteArray(),"UTF8");
    char[] xmp_arr = xmp_str.toCharArray();
    Sax.characters(xmp_arr, 0, xmp_arr.length);
    </code><code>Sax.endElement("", "basic-metadata", "basic-metadata");</code>
    <code class="jive-code jive-java">Sax.endElement("", "pdf", "pdf");
    Sax.endValidation();
    Sax.endDocument();     
    * I HAVE CHANGED MY AS PER YOUR SUGGESTION, NOW SAME RESULT HAS COMING.
    * I AM NOT ABLE TO GET THE EXACT OUTPUT.,WHY THAT ?
    Thanks,
    JavaImran{code}

  • How to update the value in xml file using transformer after setNodeValue

    Hi,
    This is my code
    I want to set update the values in xml file using transformer..
    Any one can help me
    This is my Xml file
    <?xml version="1.0" encoding="UTF-8"?>
    <place>
    <name>chennai</name>
    </place>
    Jsp Page
    <%@page contentType="text/html"%>
    <%@page pageEncoding="UTF-8"%>
    <%@ page import="javax.xml.parsers.DocumentBuilderFactory,
    javax.xml.parsers.DocumentBuilder,org.w3c.dom.*,org.w3c.dom.Element"
    %>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
    </head>
    <body>
    <% String str="";
    String str1="";
    try
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse("http://localhost:8084/XmlApplication1/sss.xml");
    out.println("Before change");
    NodeList n11 = doc.getElementsByTagName("name");
    Node n22= n11.item(0).getFirstChild();
    str1 = n22.getNodeValue();
    out.println(str1);
    out.println("After change");
    String name = "Banglore";
    NodeList nlst = doc.getElementsByTagName("name");
    Node node= nlst.item(0).getFirstChild();
    node.setNodeValue(name);
    NodeList n1 = doc.getElementsByTagName("name");
    Node n2= n1.item(0).getFirstChild();
    str = n2.getNodeValue();
    out.println(str);
    catch(Exception e)
    out.println(e) ;
    %>
    <h1><%=str%></h1>
    <%--
    This example uses JSTL, uncomment the taglib directive above.
    To test, display the page like this: index.jsp?sayHello=true&name=Murphy
    --%>
    <%--
    <c:if test="${param.sayHello}">
    <!-- Let's welcome the user ${param.name} -->
    Hello ${param.name}!
    </c:if>
    --%>
    </body>
    </html>

    hi check this exit...
    IWO10012

  • Getting error while running the XML file using XML Publisher Desktop

    Hi all,
    We have successfully loaded the XML file using XML Publisher Desktop. But when we preview the same using PDF format we are getting the following error.
    Font Dir: C:\Program Files\Oracle\XML Publisher Desktop\Template Builder for Word\fonts
    Run XDO Start
    RTFProcessor setLocale: en-us
    FOProcessor setData: C:\Documents and Settings\smanmadh\Desktop\ProductCompensationDT.xml
    FOProcessor setLocale: en-us
    java.lang.NullPointerException
         at oracle.apps.xdo.template.fo.area.PageNumber.formatString(PageNumber.java:104)
         at oracle.apps.xdo.template.fo.IDManager.registerId(IDManager.java:44)
         at oracle.apps.xdo.template.fo.area.AreaTree.registerLastPageJoinSeq(AreaTree.java:1106)
         at oracle.apps.xdo.template.fo.area.AreaTree.incrementJoinSequenceIndex(AreaTree.java:219)
         at oracle.apps.xdo.template.fo.area.AreaTree.registerLastPageDocument(AreaTree.java:1089)
         at oracle.apps.xdo.template.fo.area.AreaTree.forceOutput(AreaTree.java:471)
         at oracle.apps.xdo.template.fo.elements.FORoot.end(FORoot.java:58)
         at oracle.apps.xdo.template.fo.FOHandler.endElement(FOHandler.java:386)
         at oracle.xml.parser.v2.XMLContentHandler.endElement(XMLContentHandler.java:196)
         at oracle.xml.parser.v2.NonValidatingParser.parseElement(NonValidatingParser.java:1212)
         at oracle.xml.parser.v2.NonValidatingParser.parseRootElement(NonValidatingParser.java:301)
         at oracle.xml.parser.v2.NonValidatingParser.parseDocument(NonValidatingParser.java:268)
         at oracle.xml.parser.v2.XMLParser.parse(XMLParser.java:149)
         at oracle.apps.xdo.template.fo.FOProcessingEngine.process(FOProcessingEngine.java:279)
         at oracle.apps.xdo.template.FOProcessor.generate(FOProcessor.java:1022)
         at RTF2PDF.runRTFto(RTF2PDF.java:626)
         at RTF2PDF.runXDO(RTF2PDF.java:460)
         at RTF2PDF.main(RTF2PDF.java:251)
    Thanks in Advance.
    Sudeep.

    This is BI related. You will get a quicker answer from the BI Publisher forum
    BI Publisher

  • Error while running the XML file using XML Publisher Desktop

    Hi All,
    We have successfully loaded the XML file using XML Publisher Desktop.But when we try to preview it using the PDF format we are getting the following error.
    Font Dir: C:\Program Files\Oracle\XML Publisher Desktop\Template Builder for Word\fonts
    Run XDO Start
    RTFProcessor setLocale: en-us
    FOProcessor setData: C:\Documents and Settings\smanmadh\Desktop\ProductCompensationDT.xml
    FOProcessor setLocale: en-us
    java.lang.NullPointerException
         at oracle.apps.xdo.template.fo.area.PageNumber.formatString(PageNumber.java:104)
         at oracle.apps.xdo.template.fo.IDManager.registerId(IDManager.java:44)
         at oracle.apps.xdo.template.fo.area.AreaTree.registerLastPageJoinSeq(AreaTree.java:1106)
         at oracle.apps.xdo.template.fo.area.AreaTree.incrementJoinSequenceIndex(AreaTree.java:219)
         at oracle.apps.xdo.template.fo.area.AreaTree.registerLastPageDocument(AreaTree.java:1089)
         at oracle.apps.xdo.template.fo.area.AreaTree.forceOutput(AreaTree.java:471)
         at oracle.apps.xdo.template.fo.elements.FORoot.end(FORoot.java:58)
         at oracle.apps.xdo.template.fo.FOHandler.endElement(FOHandler.java:386)
         at oracle.xml.parser.v2.XMLContentHandler.endElement(XMLContentHandler.java:196)
         at oracle.xml.parser.v2.NonValidatingParser.parseElement(NonValidatingParser.java:1212)
         at oracle.xml.parser.v2.NonValidatingParser.parseRootElement(NonValidatingParser.java:301)
         at oracle.xml.parser.v2.NonValidatingParser.parseDocument(NonValidatingParser.java:268)
         at oracle.xml.parser.v2.XMLParser.parse(XMLParser.java:149)
         at oracle.apps.xdo.template.fo.FOProcessingEngine.process(FOProcessingEngine.java:279)
         at oracle.apps.xdo.template.FOProcessor.generate(FOProcessor.java:1022)
         at RTF2PDF.runRTFto(RTF2PDF.java:626)
         at RTF2PDF.runXDO(RTF2PDF.java:460)
         at RTF2PDF.main(RTF2PDF.java:251)
    Any pointers will be of great help.
    Thanks in Advance
    Sudeep.


    I had a similar error which when I searched, came up with this thread.
    My issue was resolved after I discovered that my RTF template was not really RTF. It was sill in MS Word DOC format. This was discovered by reviewing two templates in NOTEPAD. The MS-DOC files have a lot of "special" characters in them. My RTF was not really RTF.
    After doing a SAVE AS - RTF format, then the preview worked as expected.
    Just Sharing...
    --Tim                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Generate an XML file from a DOM tree

    Hi,
    I'm trying to generate an XML file from a DOM tree that I obtained from another XML file with the Xerces library. I used the following operation :
    public static void writeXmlFile(Document doc, String filename) {
    try {
    Source source = new DOMSource(doc);
    File file = new File(filename);
    Result result = new StreamResult(file);
    Transformer xformer = TransformerFactory.newInstance().newTransformer();
    xformer.transform(source, result);
    } catch (TransformerConfigurationException e) {
    System.err.println(e);
    System.exit(1);
    } catch (TransformerException e) {
    System.err.println(e);
    System.exit(1);
    But I have this Windows/Linux problem. When I execute this on Windows, everything is correct. But if I try on Linux (every distribution does the same thing), I obtain an XML file where everything is written on just ONE LINE : there is neither identation nor carriage return at the end of a line ... And that is pretty annoying 'cause I need to SEE what I generate ...
    Thanks for your answer,
    Blueberryfin.

    Actually I would think that no indents and no new-lines would be more correct, but maybe it's an option for parsers to do it either way if you don't specify it. If you want to specify it, look at this post from last month:
    http://forum.java.sun.com/thread.jsp?forum=34&thread=383400

  • How can we get  tag of XML file using SAX

    Hi ,
    I'm parsing one SAX parser , I'have almost done this parsing. i have faced problem for one case, i'e how can we get tag from XML file using SAX parser?
    XML file is
    <DFProperties>
    <AccessType>
    <Get/>
    </AccessType> <Description>
    gdhhd
    </Description>
    <DFFormat>
    <chr/>
    </DFFormat>
    <Scope>
    <Permanent/>
    </Scope>
    <DFTitle>gsgd</DFTitle>
    <DFType>
    <MIME>text/plain</MIME>
    </DFType>
    </DFProperties>
    I want out like GET and Permanent... means this one tag which is present inside of another tag.
    Handler class like
    public void startElement(String namespaceURI, String localName,
                   String qName, Attributes atts) throws SAXException {
    if(_ACCESSTYPE.equals(localName)){
                   accessTypeElement=ACCESSTYPE;
    public void characters(char[] ch, int start, int length)
                   throws SAXException {
    if (_ACCESSTYPE.equals(_accessTypeElement)) {
                   String strValue = new String(ch, start, length);
                   System.out.println("Accestype-----------------------------> " + strValue);
                   //System.out.println(" " + strValue);
    public void endElement(String namespaceURI, String localName, String qName)
                   throws SAXException {
    if (_ACCESSTYPE.equals(localName)) {
                   _accessTypeElement = "";
    . please any body help me

    Hi ,
    I have one problem,Please help me.
    1. How can I'll identify where exactly my Node is ended,means how how can we find corresponding nodename? in partcular place
    <Node> .............starttag1
    <NodeName>Test</NodeName>
    <Node>................starttag2
    <nodeName>test1</NodeName>
    </Node>..................endtag2
    <Node>.....................starttag3
    <NodeName><NodeName>
    <Node> .........................starttag4
    <NodeName>test4</NodeName>
    </Node>.......enddtag4
    </Node>...........end tag3
    </Node>............endtag1
    my code is below
    private final String _NODENAME = "NodeName";
    private final String _NODE = "Node";
    private String _nodeElement = "";
         private String _NodeNameElement = "";
    public void startElement(String namespaceURI, String localName,
                   String qName, Attributes atts) throws SAXException {
    if (_NODENAME.equals(localName)) {
                   NodeNameElement = NODENAME;
    if(_NODE.equals(localName)){
         System.out.println("start");
         if (_NODENAME.equals(localName)) {
                   NodeNameElement = NODENAME;
    public void characters(char[] ch, int start, int length)
                   throws SAXException {
    if (_NODENAME.equals(_NodeNameElement)) {
                   String strValue = new String(ch, start, length);
                   String sttt=strValue;
                   System.out.println("NODENAME: ************* " + strValue);
    if(_NODE.equals(_nodeElement)){
                   if (_NODENAME.equals(_NodeNameElement)) {
                        String strValue = new String(ch, start, length);
                        String sttt=strValue;
                        System.out.println("nodevalue********** " + strValue);
    public void endElement(String namespaceURI, String localName, String qName)
                   throws SAXException {
    if (_NODENAME.equals(localName)) {
                   _NodeNameElement = "";
    if(_NODE.equals(localName)){
                   System.out.println("NODENAME: %%%%%%%%%");
    please help me. How can I figure node ending for particular nodename

Maybe you are looking for

  • Documentation on Delete Material Master Data

    Hi SAPers, Is there any documentation about the process of deleting a material master record? Regards, Miguel

  • Release strategy(urgent)

    hi,    i have doubt regarding PO creation.   Purchase Order has to be approved after modidfication, but,       release strategy is not getting updated when i am modifying my PO......so i can't approve it.......... and i am chaning quantity,delivery d

  • Palm tx only works with charger plugged in

    My palm tx only works when plugged into ac charger.  Symptoms began after I left device unused for about 2 weeks.  When plugged in I get the battery charging symbol.  The battery icon says 100%.  As soon as I unplug charger, the device dies.  I have

  • Can't connect to a particular website

    When I try to connect to www.heide-express.de the browser says the server has stopped responding. I don't think it's a server issue, but a browser setting issue, and I don't know what to change? Please help! This question was solved. View Solution.

  • Is the Adobe ID and password the same as the Adobe Photoshop CC?

    I have tried to use my Adobe ID user name and password to update my CC software but it rejects it every time.  I have changed my password several times hoping this would take care of the problem but it doesn't.  Please help. I have LastPass so I know