Factory.newDocumentBuilder().parse returning DeferredDocumentImpl in servle

With respect to my earlier postregarding servlet not able to print
xml document
In Document parseXMLFile(String filename, boolean b) in servlet the line factory.newDocumentBuilder().parse(new File(filename)); is returning DeferredDocumentImpl
but the same method containing
factory.newDocumentBuilder().parse(new File(filename)); is returning XmlDocument in pain java program
why is the behaviour different
Iam able to print the elements in plain java program but in servlet if i use the same method
iam not able to print anything and returned type
is different and root element iam seeing as nul
could anybody please help
thanks
BHanu

Did the suggestion in http://swforum.sun.com/jive/thread.jspa?threadID=64634 not help?
(That is 'factory.setAttribute("http://apache.org/xml/features/dom/defer-node-expansion", (false));')

Similar Messages

  • (DocumentBuilder).parse return null under jdk 1.5.0

    I would like to understand why the following code return a correct Document instance if it running under jdk 1.4.2 and instead return null if it running under jdk 1.5.0.
    Thanks!
    F.
    import java.io.IOException;
    import java.io.StringReader;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import org.w3c.dom.Document;
    import org.xml.sax.InputSource;
    import org.xml.sax.SAXException;
    String test = "<root>" + "" + "</root>";
    StringReader sreader = new StringReader (test);
    InputSource is = new InputSource(sreader);
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder;
    builder = factory.newDocumentBuilder();
    Document doc =  builder.parse(is);
    System.out.println("Document is: " + doc);

    Because you're using the toString() method to display the Document. It works differently in Java 5 than it did in Java 1.4. This is perfectly okay because the DOM specification doesn't say anything about what the toString() method should return. If you relied on that for anything other than debugging then you were relying on an undocumented feature. Shouldn't do that.

  • Builder.parse return null under jdk 1.5.0

    I would like to understand why the following code return a correct Document instance if it running under jdk 1.4.2 and instead return null if it running under jdk 1.5.0.
    Thanks!
    F.
    String test = "<root>" + "" + "</root>";
    StringReader sreader = new StringReader (test);
    InputSource is = new InputSource(sreader);
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder;
    builder = factory.newDocumentBuilder();
    Document doc =  builder.parse(is);
    System.out.println("Document is: " + doc);

    Because you're using the toString() method to display the Document. It works differently in Java 5 than it did in Java 1.4. This is perfectly okay because the DOM specification doesn't say anything about what the toString() method should return. If you relied on that for anything other than debugging then you were relying on an undocumented feature. Shouldn't do that.

  • Sax parser returned an exception while trying to print/export in PDF

    Hi all ,
    I am getting an error as below when I am trying to export and print my report in PDF and also into POWERPOINT.
    Sax parser returned an exception. Message: Entity 'nbsp' was not found, Entity publicId: , Entity systemId: , Line number: 40, Column number: 511
    Error Details
    Error Codes: UH6MBRBC
    Location: saw.subsystem.pdf.postprocess, saw.subsystem.portal.pdf, saw.httpserver.processrequest, saw.rpc.server.responder, saw.rpc.server, saw.rpc.server.handleConnection, saw.rpc.server.dispatch, saw.threadpool, saw.threadpool, saw.threads
    This is in my QA environment.I have the same report in my local and that seems to be working fine without any errors.I saw an OTN thread below but that says they are using static text with html codes in their reports and that is causing the error..But I don't have any static text in my reprot.it is a Pivot table with combine with similar request.Also one more thing is I am getting this error all of sudden this morning..I have 8 more reports and they seem to be working fine.
    Error when trying to use the "Print to PDF" option
    Any suggestions please

    Hi Satya,
    I am facing the same issue. but I am facing this issue with Mozilla Firefox browser only. If I modify same reports in internet explorer I don't get this error.  It seems this issue is with OBIEE 10g version only and Oracle has provided some patches on this in OBIEE 11g .
    You have posted this question long back. If you have got any solution for this then please let me know also.
    Thanks

  • Sax parser returned an exception. Message: Invalid character (Unicode: 0x12

    Hi,
    I'm getting the error 'Sax parser returned an exception. Message: Invalid character (Unicode: 0x12), Entity publicId: , Entity systemId: , Line number: 47, Column number: 75'
    when I try and run a report in BI Answers 10g.
    Apparently it's to do with a Java applet (or piece of Java code anyway) not being sent to an exception so it can't handle it. The problem is that I can't
    run the report to get at some of the views that seem only available at run time. eg. charts.
    Does anyone know how I can see behind the scenes of views without running the report?
    Or does anyone know how to get rid of this error anyway?
    Many thanks,
    - Jenny

    Hi Satya,
    I am facing the same issue. but I am facing this issue with Mozilla Firefox browser only. If I modify same reports in internet explorer I don't get this error.  It seems this issue is with OBIEE 10g version only and Oracle has provided some patches on this in OBIEE 11g .
    You have posted this question long back. If you have got any solution for this then please let me know also.
    Thanks

  • Report Result error Sax parser returned an exception

    Hi,
    I'm using Oracle Business Intelligence 10.1.3.4.2.
    Recently I changed the BI instance to another server. So that I copied the reports from Old server to New server.
    Reports are working fine in new server. But while trying to modify that reports it is showing error
    "Sax parser returned an exception. Message: Invalid character (Unicode: 0x13), Entity publicId: , Entity systemId: , Line number: 1, Column number: 10737"
    Error Codes: UH6MBRBC:E6MUPJPH
    Regards,
    Satya

    Hi Satya,
    I am facing the same issue. but I am facing this issue with Mozilla Firefox browser only. If I modify same reports in internet explorer I don't get this error.  It seems this issue is with OBIEE 10g version only and Oracle has provided some patches on this in OBIEE 11g .
    You have posted this question long back. If you have got any solution for this then please let me know also.
    Thanks

  • XML Parser returning XML content

    This probably seems like overkill..
    Im building a JSP that reads in XML and parses it. I then need to filter for specific values in the XML, and return a chunk of the XML to the output stream.
    So far I've got..
          //set-up in and content-type
            FileInputStream file = new FileInputStream (getServletContext().getRealPath("/games_arcade/xml/game_marketing_content.xml"));
            //response.setContentType("text/xml");
            //parse the request
            Document doc = null ;
            try {
                   DocumentBuilderFactory docBuilderFact = DocumentBuilderFactory.newInstance();
                   DocumentBuilder docBuilder = docBuilderFact.newDocumentBuilder();
                   doc = docBuilder.parse(file);
                   out.println("Go on ya good thing!!!");
            } catch (ParserConfigurationException pcEx) {
                throw new ServletException("jaxp not configured!", pcEx);
            //get needed data from the xml
            NodeList games = doc.getElementsByTagName("game");
              out.println(output.toString());
              Now Im lost. All the requisites are there, imports etc, Im just stuck with filtering the NodeList.
    Or am I completely wrong with this approach?
    Any help greatly appreciated.
    thanks!
    Stephen

    Hi,
    thanks for the replyand suggestions. Have a bit of an issue with this method, this method (due to technical limitations) is completely JSP, using a standard iPlanet 6.1 classpath. I cant deploy WAR's (and cant use taglibs). Xpath/XSL would be ideal, but how do I write the output as XML?
    So are you suggesting
    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
      <xsl:output method="html"/>
        <xsl:template match="/">
            <xsl:for-each select="games/game">
              <xsl:if test="@id = $GAMEID">
                   ... output the xml node using value-of's etc...
              </xsl:if>
            </xsl:for-each>
          </xsl:template>
        </xsl:stylesheet>Cheers Dr Clap!
    Stephen

  • RFC Lookup - Best Approach To Parse Returned Tables

    Hi Everyone,
    We are doing some RFC Lookups at a header node that are returning tables for all of the items (for performance reasons).  I am trying to figure out what the best way to extract the values from the table, which is most of time has more than 1 key column.  At the moment I am doing this through DOM, but I have also heard about using arrays, and have even seen an example of using a hashtables with all of the values concatenated together to later parse out using substrings.  I'm looking for the best approach to:
    1) Store this data as some kind of global object to lookup during the header
    2) Search and Parse from the global object during linte items.
    As an example, I have the following lines in my table:
    Key1,Key2,Value1,Value2,Value3
    A,A,1,2,3
    A,B,1,2,4
    A,C,3,4,2
    B,A,2,4,6
    And during line item processing I may want to find the value for Key1=A, Key2=C.
    Thanks
    Peter

    Hi Peter,
    Please take a look at these...
    https://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/com.sap.km.cm.docs/library/xi/xi-code-samples/xi%20mapping%20lookups%20rfc%20api.pdf
    /people/siva.maranani/blog/2005/08/23/lookup146s-in-xi-made-simpler
    /people/sravya.talanki2/blog/2005/12/21/use-this-crazy-piece-for-any-rfc-mapping-lookups
    /people/alessandro.guarneri/blog/2006/03/27/sap-xi-lookup-api-the-killer
    cheers,
    Prashanth
    P.S Please mark helpful answers

  • X:parse returning [#document: null]

    the following code is outputting [#document: null]
         <c:import var="sampleXML" url="../common/sample.xml" />
         <x:parse xml="${sampleXML}" var="parsedXML" />
    yet, if it c:out the variable sampleXML, it spits out the xml I have in the sample.xml file. any thoughts why this might be happening?
    thanks.

    ya, it's valid, and im just using <c:out value="${parsedXML}" />
    it's weird though. on my local i copy and pasted whats done here:
    http://www.java2s.com/Code/Java/JSTL/JSTLparseXMLdocument.htm
    and it still doesn't work, which would lead me to believe that it must be some config on my server? any thoughts?

  • Help: SQL query when parsed returns Invalid Identifier error

    Hi The expression posted below is the actual SQL Expression which is required in my report:
    ((select name from (
    select loc_id,name,row_number()over(  order by r)  rn from (
    SELECT 0, loc_id, Misc1_txt  NAME,'A' STATUS ,rownum r
                        FROM dvxloc
                       WHERE loc_id = "XXXLOC"."LOC_ID"
                       union
    SELECT     parent_loc_id, loc_id, (SELECT a.Misc1_txt
                                                         FROM dvxloc a
                                                        WHERE a.loc_id =b.loc_id) NAME,'B' ,ROWNUM
                            FROM dvxlocpath b
                      START WITH b.loc_id = "XXXLOC"."LOC_ID"
                      CONNECT BY PRIOR  parent_loc_id=loc_id
    )                where name is NOT NULL        order by STATUS, R
    ) where rn = 1))
    It gives an error while parsing: "XXXLOC"."LOC_ID" invalid identifier
    LOC_ID is of numeric data type in the database. and when I run thi query in SQL editor after replacing "XXXLOC"."LOC_ID" with a numeric value say 456 . The query can be put as
    ((select name from (
    select loc_id,name,row_number()over(  order by r)  rn from (
    SELECT 0, loc_id, Misc1_txt  NAME,'A' STATUS ,rownum r
                        FROM dvxloc
                       WHERE loc_id = 456                   union
    SELECT     parent_loc_id, loc_id, (SELECT a.Misc1_txt
                                                         FROM dvxloc a
                                                        WHERE a.loc_id =b.loc_id) NAME,'B' ,ROWNUM
                            FROM dvxlocpath b
                      START WITH b.loc_id = 456                  CONNECT BY PRIOR  parent_loc_id=loc_id
    )                where name is NOT NULL        order by STATUS, R
    ) where rn = 1))
    The above query runs flawlessly in a SQL editor. and also this is parsed by the crystal sql expression editer
    I'm totally messed up of looking for altenatives. I have to deliver a report to the client and stuck on this part only.
    The below query parses perfectly in crystal:
    (select locname
    from dvxloc where loc_id in(select loc3 from dvxlocpath
    where loc_id = "XXXLOC"."LOC_ID"))
    Edited by: vipulbhatia29 on May 8, 2009 11:06 AM
    Edited by: vipulbhatia29 on May 8, 2009 11:14 AM

    You said the above works in SQL Editor but does your original work?
    ((select name from (
    select loc_id,name,row_number()over( order by r) rn from (
    SELECT 0, loc_id, Misc1_txt NAME,'A' STATUS ,rownum r
    FROM dvxloc
    WHERE loc_id = "XXXLOC"."LOC_ID"
    union
    SELECT parent_loc_id, loc_id, (SELECT a.Misc1_txt
    FROM dvxloc a
    WHERE a.loc_id =b.loc_id) NAME,'B' ,ROWNUM
    FROM dvxlocpath b
    START WITH b.loc_id = "XXXLOC"."LOC_ID"
    CONNECT BY PRIOR parent_loc_id=loc_id
    ) where name is NOT NULL order by STATUS, R
    ) where rn = 1))
    Crystal does nothing to the SQL in the command editor, what you type in is what we pass.
    What database are you connecting to? And if it has a tracing tool what SQL are you seeing from Crystal when you try to run the report?

  • Problem in parsing

    Hi i am trying to parse a HTML document, but i am not able to that correctly...
    here is my source cose
    package com.wolfram.nutch.parse;
    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    import org.apache.nutch.parse.HTMLMetaTags;
    import org.apache.nutch.parse.HtmlParseFilter;
    import org.apache.nutch.parse.Parse;
    import org.apache.nutch.protocol.Content;
    import java.util.Enumeration;
    import java.util.Properties;
    import org.apache.hadoop.conf.Configuration;
    import org.w3c.dom.DocumentFragment;
    import org.w3c.dom.*;
    import org.xml.*;
    import javax.xml.parsers.*;
    import javax.xml.transform.*;
    import javax.xml.transform.dom.*;
    import javax.xml.transform.stream.*;
    import java.io.*;
    import org.apache.xerces.parsers.DOMParser;
    /** Adds basic searchable fields to a document. */
    public class WolframHtmlParseFilter implements HtmlParseFilter {
         public static final Log LOG = LogFactory
                   .getLog(WolframHtmlParseFilter.class);
         private Configuration conf;
         public static final String META_KEYWORDS_NAME = "keywords";
         public static final String META_SUMMARY_NAME = "summary";
        public static final String META_SYNONYMS_NAME = "synonyms";
         public Parse filter(Content content, Parse parse, HTMLMetaTags metaTags,
                   DocumentFragment doc) {
              // Trying to find the document's recommended term
              String keywords = null;
              String summary = null;
            String synonyms = null;
            Document d = doc.getOwnerDocument();
          String htmlfile = content.toString();
          //String htmlfile = "<html><title></title><img /> <img /><img /></html>";
          Reader reader;
          Document actualdoc = null;
          DOMParser parser = new DOMParser();
          try {
    //           Create a factory
              DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    //           Use document builder factory
              DocumentBuilder builder = factory.newDocumentBuilder();
    //          Parse the document
              reader=new CharArrayReader(htmlfile.toCharArray());
              parser.parse(new org.xml.sax.InputSource(new StringReader(htmlfile)));
              actualdoc = parser.getDocument();
          catch(Exception e) {
              System.err.println(e);
          System.out.println("the string is" + actualdoc);
          NodeList images = actualdoc.getElementsByTagName("img");
          int length = images.getLength();
          System.out.println("the length is" + length);
          for(int i = 0;i<length;i++)
              Node image = images.item(i);
              String nodename = image.getNodeName();
              String alttext = image.getAttributes().getNamedItem("alt").getNodeValue();
              System.out.println(alttext);
              if (!metaTags.getNoIndex()) {
                   Properties generalMetaTags = metaTags.getGeneralTags();
                   for (Enumeration tagNames = generalMetaTags.propertyNames(); tagNames
                             .hasMoreElements();) {
                        Object element = tagNames.nextElement();
                        if (element.equals("keywords")) {
                             keywords = generalMetaTags.getProperty("keywords");
                        if (element.equals("dc.keywords")) {
                             keywords = generalMetaTags.getProperty("dc.keywords");
                        if (element.equals("description")) {
                             summary = generalMetaTags.getProperty("description");
                        if (element.equals("dc.description")) {
                             summary = generalMetaTags.getProperty("dc.description");
                             System.out.println("in dc.Description");
                    if (element.equals("synonyms")){
                        synonyms = generalMetaTags.getProperty("synonyms");
                   if (keywords != null) {
                        parse.getData().getParseMeta()
                                  .set(META_KEYWORDS_NAME, keywords);
                   if (summary != null) {
                        parse.getData().getParseMeta().set(META_SUMMARY_NAME, summary);
                if (synonyms != null){
                    parse.getData().getParseMeta().set(META_SYNONYMS_NAME, synonyms);
              return parse;
         public void setConf(Configuration conf) {
              this.conf = conf;
         public Configuration getConf() {
              return this.conf;
    and the error i am getting is[Fatal Error] :1:1: Content is not allowed in prolog.
    org.xml.sax.SAXParseException: Content is not allowed in prolog.
    the string isnull
    any ideas please....i am stuck on this problem from last 3 days.....
    any help is highly appreciated...thanks                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    Obviously, don't use an XML parser for something that isn't XML. Either switch over to using an HTML parser that produces a DOM, or clean up the HTML beforehand so that it's well-formed XHTML.
    Look at JTidy and TagSoup.

  • Loading XML file for parsing

    Folks,
    I have placed one xxx.XML file under /WEB-INF/ of my application server and i have configured a servlet in web.xml file to execute during server startup like below
    <servlet>
    <servlet-name>MonitorInitServlet</servlet-name>
    <servlet-class>com.xxx.xxx..services.MonitorInitServlet</servlet-class>
    <init-param>
    <param-name>configFile</param-name>
    <param-value>/WEB-INF/portalMonitorConfig.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
    </servlet>
    And the above servlet loads portalMonitorConfig.xml file and i have below code
    InputStream inputStream = xxx.class.getResourceAsStream("/WEB-INF/portalMonitorConfirg.xml");
    private static Document parseXmlFile(InputStream xml) throws SAXException, IOException,
    ParserConfigurationException
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(false);
    return factory.newDocumentBuilder().parse(xml);
    So when i do the above , i get
    java.lang.IllegalArgumentException :InputStream cannot be null,
    I know its sending a null InputStream, By the way i need to know what is the issue in the above code when i create InputStream object
    InputStream inputStream = xxx.class.getResourceAsStream("/WEB-INF/portalMonitorConfig.xml");
    Any help with the code is really appreciated

    when serializing the DOM, use this: transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, scrReg.dtd");
    Merry Chrasmas too ;-)

  • XML Parsing (newbie) confused

    I am trying parse an xml file and look for a particualr part. But I can't seem to get the output to look correct. I have attached my code and output below as well as the xml and dtd files.
    What I want to do is take the partnumber if it exists in my xml file and then show the url link... when I do my normal jdbc query.
    import java.io.IOException;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import org.w3c.dom.Text;
    import org.xml.sax.SAXException;
    public class XMLParser {
        public static void main(String[] args) {
            Document doc = parseXmlFile("c:/monarch.xml", false);
              NodeList nodelist = doc.getElementsByTagName("part");
              System.out.println("nodelist size is " + nodelist.getLength());
              // got the nodelist of "part"
              for(int a=0; a<nodelist.getLength(); a++) {
                   Node node = nodelist.item(a);                                                  // this is the "part"
                   // loop through the childs
                   NodeList nodelist2 = node.getChildNodes();
                   for(int b=0; b<nodelist2.getLength(); b++) {                              // child length is "4" correct
                       Node node2 = nodelist2.item(b);
                        System.out.println("Nodename is " + node2.getNodeName());
                        System.out.println("Nodename is " + node2.getNodeValue());
        public static Document parseXmlFile(String filename, boolean validating) {
            try {
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                factory.setValidating(validating);
                Document doc = factory.newDocumentBuilder().parse(new File(filename));
                return doc;
            } catch (SAXException e) {
                e.getMessage();
            } catch (ParserConfigurationException e) {
                 e.getMessage();
            } catch (IOException e) {
                 e.getMessage();
            return null;
    }Output:
    nodelist size is 2
    Nodename is #text
    Nodename is
    Nodename is partnumber
    Nodename is null
    Nodename is #text
    Nodename is
    Nodename is sku
    Nodename is null
    Nodename is #text
    Nodename is
    Nodename is cost
    Nodename is null
    Nodename is #text
    Nodename is
    Nodename is link
    Nodename is null
    Nodename is #text
    Nodename is
    Nodename is #text
    Nodename is
    Nodename is partnumber
    Nodename is null
    Nodename is #text
    Nodename is
    Nodename is sku
    Nodename is null
    Nodename is #text
    Nodename is
    Nodename is cost
    Nodename is null
    Nodename is #text
    Nodename is
    Nodename is link
    Nodename is null
    Nodename is #text
    Nodename is
    My XML File:
    <?xml version="1.0" encoding="ISO-8859-1"?><!DOCTYPE catalog SYSTEM "file:///c:/monarch.dtd">
    <catalog>
         <part>
              <partnumber>xyz</partnumber>
              <sku>450252</sku>
              <cost>37.25</cost>
              <link>http://www.test.com/</link>
         </part>
         <part>
             <partnumber>abc</partnumber>
              <sku>220251</sku>
              <cost>18.50</cost>
              <link>http://www.test.com/</link>
         </part>
    </catalog>
    [\code]
    and DTD<?xml encoding="UTF-8"?>
    <!ELEMENT catalog (part)+>
    <!ATTLIST catalog
    xmlns CDATA #FIXED ''>
    <!ELEMENT part (partnumber,sku,cost,link)>
    <!ATTLIST part
    xmlns CDATA #FIXED ''>
    <!ELEMENT partnumber (#PCDATA)>
    <!ATTLIST partnumber
    xmlns CDATA #FIXED ''>
    <!ELEMENT sku (#PCDATA)>
    <!ATTLIST sku
    xmlns CDATA #FIXED ''>
    <!ELEMENT cost (#PCDATA)>
    <!ATTLIST cost
    xmlns CDATA #FIXED ''>
    <!ELEMENT link (#PCDATA)>
    <!ATTLIST link
    xmlns CDATA #FIXED ''>
    How can I get it so that I can loop through the list and when I come to say part abc... I can do something with those 4 entries?
    Thanks for any help.

    BTW I noticed that your error handling in parseXmlFile probably doesn't do what you want / expect it to. Fixed in the code in this post.
    There is an alternative to iterating through the children manually, and that's to use XPath. import java.io.*;
    import java.util.*;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import javax.xml.xpath.*;
    import org.w3c.dom.Document;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import org.xml.sax.SAXException;
    public class XMLParser {
        public static void main(String[] args) {
            Map<String, String> urlByPartNo = new HashMap<String, String>();
            XPath xpath = XPathFactory.newInstance().newXPath();
            Document doc = parseXmlFile("monarch.xml", false);
            NodeList nodelist = doc.getElementsByTagName("part");
            try
                for (Node partNode : wrap(nodelist))
                    String partNo = xpath.evaluate("partnumber/text()", partNode);
                    String url = xpath.evaluate("link/text()", partNode);
                    if (partNo != null && url != null)
                        urlByPartNo.put(partNo, url);
            catch (XPathException xpe)
                System.out.println(xpe);
            System.out.println("Read following map: " + urlByPartNo);
        public static Document parseXmlFile(String filename, boolean validating) {
            try {
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                factory.setValidating(validating);
                Document doc = factory.newDocumentBuilder().parse(new File(filename));
                return doc;
            } catch (SAXException e) {
                System.err.println(e.getMessage());
            } catch (ParserConfigurationException e) {
                System.err.println(e.getMessage());
            } catch (IOException e) {
                System.err.println(e.getMessage());
            return null;
         * Helper method to all foreach to be applied to <code>NodeList</code>s.
         * @param list A nodelist over which we'd like to iterate.
         * @return An <code>Iterable</code> which can plug straight into a foreach.
        private static Iterable<Node> wrap(final NodeList list)
            return new Iterable<Node>()
                    // javadoc inherited.
                    public Iterator<Node> iterator()
                        return new Iterator<Node>()
                             * The current index - i.e. that which will be accessed
                             * by the next call to {@link #next()}.
                            private int curr = 0;
                             * The length of the nodelist.
                            private int length = list.getLength();
                            // javadoc inherited
                            public boolean hasNext()
                                return curr < length;
                            // javadoc inherited
                            public Node next()
                                return list.item(curr++);
                            // javadoc inherited
                            public void remove()
                                // There's no way to support removal, even if I
                                // wanted to.
                                throw new UnsupportedOperationException();
    }

  • Vc webdynpro DOM parsing

    hello there
    i tryed the DOM parsing on the returned paramter from the <u>portal eventing</u>
    between<u> visual composer and webdynpro</u> and i get this error :
    <b>com.sap.engine.lib.xml.parser.ParserException: XMLParser: No data allowed here:
    (hex) 25, 33, 43(:main:,row:1,col:3</b>
    the ascii code from the visual composer in dataObject is:
    %3CParamas%20version%3D%222%22%20%3E%3CRow%20STR1%3D%22test1%22%20/%3E%3C/Params%3E
    the xml code of dataObject string is:
    <b><Params version="2"><Row STR1="test1"\><\Params></b>
    the java code is:
    // Create a Dom parser
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(true);
    DocumentBuilder docBuilder = factory.newDocumentBuilder();
    // Parse input to create document tree
    StringReader s = new StringReader(dataObject);
    InputSource is = new InputSource(s);
    Document doc = docBuilder.parse(is);

    thanx but i fixed the problem my self the problem was in visual composer out put xml its sent a '/' insted of '\' in the xml syntax

  • Can we use javax.xml.parser API's from j2sdk kit?

    Hi All,
    I am new to this jaxp API's and my first doubt is Can I use the javax.xml.parser API which come bundled with j2sdk-1.4.1 or Should I install JWSDP-1.3 to get to javax.xml.parsers API?
    Thanks

    Hi,
    I am trying to read an xml file on Solaris.
    Can we not use doc.getElementById(String elementID) after deriving doc obejct ?
    Here is the code I am trying to use:
    try
    factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(false);
    File file = new File("/command/parse_doc.xml");
    doc = factory.newDocumentBuilder().parse(file); //upto here it works
    Element element = doc.getElementById("Topics");
    String name = element.getTagName(); //returns nothing but throws exception "null"
    }catch(Exception exe){
    out.println("Exception:" + exe.getMessage());}
    here I get no such element, and the try catch block exception also null.
    Is there something I am missing?
    DO I have to call doc.getDocumentElement() before I call get ElementBy ID() and if so why?
    Thanks.

Maybe you are looking for

  • Find the number of concurrent users in system at a given time

    Hi All, We have the ECC system in which we need to set up monitoring alert which should tell the following things. 1.The  number of concurrent users looged  currently in the system. 2. List of  transaction per hour or user activites with the counts I

  • BPM question - Delete all entries in a table and Insert data

    Hello, I'm new to PI BPM and have this scenario to implement. I'm supposed to delete all entries in a table and then insert data to the same table. Is BPM necessary? If it is, what is the best practice to implement my scenario? I want to make sure th

  • ISE 1.2 step-by-step patch or direct to latest....and IPEP does it get any patches?

    I am currently running ISE 1.1.3u1 Since I will basically have to redo my IPEPs to renew our SSL Certs, I am planning to just move up to 1.2. Questions I have are: Is there not a FULL install for 1.2u"latest"? From my understanding I should be able t

  • No 'Low-Battery' Warning on iPhone 4

    Don't know whether to class this as a hardware, or software fault, however... As the title says, I get no little blue rectangle warning at either 20% or 10%. I have deliberately ran the battery down for the last 4 days in a row to (quadruple?) check

  • Message Mapping Design Question

    I have to parse from a source field (x) and map to this structure: <Line>   <Number\>   <Descr\>   <Code\> </Line> The source field is a string that contains newline characters (just a blob of text).  Example: ABC\nLine 1,widget, 123A\nXYZ\nLine 2,ga