How to ignore DOCTYPE when parsing xml java?

Hello
i am trying to parse some sml files that have:
<!DOCTYPE ModuleRoot SYSTEM "C:\xxx\xmlapp.dtd">
i don;t have the dtd file
how can i ignore it by changing my code and not changing the xml file.
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
this.doc = documentBuilder.parse(xmlFileName);
i got exception in this.doc = documentBuilder.parse(xmlFileName);
(The system cannot find the path specified)
Thanks in advance.

You need to create an EntityResolver that returns a dummy DTD. Since you aren't actually validating, this can be as simple as:
        db.setEntityResolver(new EntityResolver()
            public InputSource resolveEntity(String publicId, String systemId)
                throws SAXException, IOException
                return new InputSource(new StringReader(""));
        });For more information, here's an article that I wrote on [XML parsing and validation|http://www.kdgregory.com/index.php?page=xml.parsing].

Similar Messages

  • How to apply condition when parsing XML using XMLTable

    Oracle Database 11g Enterprise Edition Release 11.1.0.7.0 - 64bit Production
    PL/SQL Release 11.1.0.7.0 - Production
    CORE 11.1.0.7.0 Production
    TNS for Linux: Version 11.1.0.7.0 - Production
    NLSRTL Version 11.1.0.7.0 - Production
    XML Response to be processed by stored proc:
    <TFSResponse>
    <TFS>
              <referenceNumber>39760</referenceNumber>
              <reqId>39760</reqId>
              <fromAccount>
                   <id>1550796</id>
                   <number>0003210011</number>
              </fromAccount>
              <toAccount>
                   <id>1550769</id>
                   <number>3199109643</number>
              </toAccount>
              <createdBy>
                   <userId>627892</userId>
                   <userLoginId>AAAAAA</userLoginId>
                   <userTypeId>1</userTypeId>
              </createdBy>
              </TFS>
    </TFSResponse>
    Register schema script:
    DECLARE
    l_schema CLOB;
    BEGIN
    l_schema := '<?xml version="1.0" encoding="UTF-8"?>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:xdb="http://xmlns.oracle.com/xdb">
    <xs:element name="TFSResponse" type="TFSResponseWSResponseType" xdb:defaultTable="TEMP_RESULT" />
         <xs:complexType name="TFSResponseWSResponseType">
              <xs:sequence>
              <xs:element maxOccurs="unbounded" name="TFS" type="TFSSummaryWSTO"/>
              </xs:sequence>
         </xs:complexType>
         <xs:complexType name="TFSSummaryWSTO">
              <xs:sequence>
                   <xs:element name="referenceNumber" type="xs:string"/>
                   <xs:element name="reqId" type="xs:long"/>
                   <xs:element name="fromAccount" type="tns:AccountSummaryWSTO" />
    <xs:element name="toAccount" type="tns:AccountSummaryWSTO"/>
                   <xs:element name="createdBy" type="tns:userWSTO"/>
              </xs:sequence>
         </xs:complexType>
         <xs:complexType name="AccountSummaryWSTO">
              <xs:sequence>
                   <xs:element minOccurs="1" name="accountId" type="xs:long" />
                   <xs:element minOccurs="1" name="accountNumber" type="xs:string" />
              </xs:sequence>
         </xs:complexType>
         <xs:complexType name="userWSTO">
              <xs:sequence>
                   <xs:element name="userId" type="xs:long" />
                   <xs:element name="userLoginId" type="xs:string" />
                   <xs:element name="userTypeId" type="xs:short" />
              </xs:sequence>
         </xs:complexType>
    </xs:schema>';
    dbms_xmlSchema.registerSchema(schemaurl => 'TFSWebService_schema.xsd',
    schemadoc => l_schema,
    enableHierarchy => dbms_xmlschema.ENABLE_HIERARCHY_NONE);
    END;/
    Object Type:
    CREATE OR REPLACE TYPE DOC_ROWTYPE AS OBJECT
    REFERENCENUMBER VARCHAR2(255),
    REQID NUMBER(12),
    FROMACCOUNTID NUMBER(12),
    FROMACCOUNTNUMBER VARCHAR2(35),
    TOACCOUNTID NUMBER(12),
    TOACCOUNTNUMBER VARCHAR2(35),
    CREATEDBYUSERID NUMBER(12),
    CREATEDBYUSERLOGINID VARCHAR2(12)
    Collection Type:
    CREATE OR REPLACE TYPE DOC_TABLETYPE IS TABLE OF DOC_ROWTYPE;
    CREATE OR REPLACE PROCEDURE SP_TFS_REPORT (LoginId IN STRING,
    requestedByUser IN STRING,
    result_cursor OUT SYS_REFCURSOR)
    IS
    SYSTEM_USER VARCHAR2(12) := 'SYSTEM';
    l_http_request UTL_HTTP.req;
    l_http_response UTL_HTTP.resp;
    l_string_request VARCHAR2(1024);
    l_result_xml XMLTYPE;
    docExtTable_XML DOC_TABLETYPE := DOC_TABLETYPE();
    docExtRecord DOC_ROWTYPE;
    BEGIN
    l_string_request := .....(prepare web service request here)
    l_http_response := UTL_HTTP.get_response(l_http_request);
    resp_in_xml := XMLTYPE(l_clob_response);
    INSERT INTO TEMP_RESULT VALUES l_result_xml;
    SELECT DOC_ROWTYPE (t1.referenceNumber, t1.reqId, t2.accountId, t2.accountNumber, t3.accountId, t3.accountNumber,
                                                 t4.userLoginId, t4.userId)
    BULK COLLECT INTO docExtTable_XML
    FROM TEMP_RESULT ltr,
    XMLTABLE('/TFSResponse/TFS'
    PASSING ltr.object_value
    COLUMNS
    referenceNumber VARCHAR2(255 BYTE) PATH 'referenceNumber',
    reqId NUMBER(12)                PATH 'reqId',
    fromAccountXML XMLTYPE PATH 'fromAccount',
    toAccountXML XMLTYPE      PATH 'toAccount',
    createdByXML XMLTYPE      PATH 'createdBy'
    ) t1,
    XMLTABLE('/fromAccount'
    PASSING t1.fromAccountXML
    COLUMNS
    accountId NUMBER(12) PATH 'accountId',
    accountNumber VARCHAR2(35 BYTE) PATH 'accountNumber'
    ) t2,
    XMLTABLE('/toAccount'
    PASSING t1.toAccountXML
    COLUMNS
    accountId NUMBER(12) PATH 'accountId',
    accountNumber VARCHAR2(35 BYTE) PATH 'accountNumber'
    ) t3,
    XMLTABLE('/createdBy'
    PASSING t1.createdByXML
    COLUMNS
    userId NUMBER(12) PATH 'userId',
    userLoginId VARCHAR2(12 BYTE) PATH 'userLoginId' ----- This value should be set based on a condition*
    ) t4
    OPEN result_cursor FOR SELECT * FROM TABLE (DOC_TABLETYPE);
    COMMIT;
    END SP_TFS_REPORT
    The condition is like this
    IF (requestedByUser = true and createdByUserType = '2') then
    CREATEDBYUSERLOGINID := SYSTEM_USER;
    ELSE
         Take CREATEDBYUSERLOGINID from XML value 'userLoginId'
    where 'requestedByUser' is the input parameter to the stored procedure and 'createdByUserType' is the value from XML.
    'userTypeId' is not required to be set in collection.
    Now my question is how to put that condition when doing the XML parsing.
    Edited by: 991900 on Mar 19, 2013 9:54 AM

    Add a projection for "userTypeId" in T4, then use a CASE statement in the SELECT clause :
    SELECT  DOC_ROWTYPE (
            t1.referenceNumber, t1.reqId, t2.accountId, t2.accountNumber, t3.accountId, t3.accountNumber,
                                            t4.userId,
            CASE WHEN requestedByUser = 'true' AND t4.userTypeId = 2
                      THEN system_user
                 ELSE t4.userLoginId
            END
    BULK COLLECT INTO docExtTable_XML
        FROM TEMP_RESULT ltr,
        XMLTABLE('/TFSResponse/TFS'
                   PASSING ltr.object_value
                   COLUMNS
                       referenceNumber    VARCHAR2(255 BYTE)        PATH 'referenceNumber',
                       reqId              NUMBER(12)                   PATH 'reqId',                                       
                       fromAccountXML      XMLTYPE                  PATH 'fromAccount',                 
                       toAccountXML        XMLTYPE                     PATH 'toAccount',
                       createdByXML       XMLTYPE                     PATH 'createdBy'                                       
                    ) t1,
        XMLTABLE('/fromAccount'
                   PASSING t1.fromAccountXML
                   COLUMNS
                       accountId              NUMBER(12)    PATH 'accountId', 
                       accountNumber     VARCHAR2(35 BYTE)  PATH 'accountNumber'                                       
                   ) t2,
        XMLTABLE('/toAccount'
                   PASSING t1.toAccountXML
                   COLUMNS
                       accountId            NUMBER(12)    PATH 'accountId', 
                       accountNumber   VARCHAR2(35 BYTE)  PATH 'accountNumber'
                   ) t3,
        XMLTABLE('/createdBy'
                   PASSING t1.createdByXML
                   COLUMNS
                       userId           NUMBER(12)        PATH 'userId',
                       userLoginId      VARCHAR2(12 BYTE) PATH 'userLoginId',
                       userTypeId       NUMBER            PATH 'userTypeId'
                   ) t4
        ;

  • How to add doctype when generating XML from an arbitrary data structure

    I was reading SUN's tutorial "Working with XML - PART IV: Using XSLT". Inside this tutorial, in 3, it talks about how to generate XML from an arbitrary data structure making use of a XMLReader and a Transformer. The example only shows adding elements. Is there a way to add DTD information in the XML generated, i.e. <!DOCTYPE ... >? What APIs can I use?
    Thanks,
    Alex

    The simplest way seems to me is to use a XSL file for that. The <xsl:output> attributes doctype-system and doctype-public generate the DTD declaration <!DOCTYPE YOUR_ROOT SYSTEM "yourDTDfile.dtd"> and <!DOCTYPE YOUR_ROOT PUBLIC "yourDTDfile.dtd">, respectively.
    When calling transformerInstance.transform() the XSLT processor performs the identity transformation - it just copies elements, attributes, content, processing instructions and comments to the result stream.
    If you're using an xsl file for your transformation already, simply add <xsl:output doctype-system="yourDTDfile.dtd"/> to your existing XSL file.
    If you're only using the identity transformation you'd need to change the line of code where you obtain the transformer instance from the TransformerFactory to:
    t_factory.newTransformer(new StreamSource("test.xsl"));
    and use this as test.xsl:
    <?xml version="1.0"?>
    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
       <xsl:output doctype-system="yourDTDfile.dtd"/>
       <!-- this is the identity transformation -->
       <xsl:template match="*|@*|comment()|processing-instruction()|text()">
          <xsl:copy>
             <xsl:apply-templates select="*|@*|comment()|processing-instruction()|text()"/>
          </xsl:copy>
       </xsl:template>
    </xsl:stylesheet>Good luck.

  • How get DOCTYPE name when parsing XML Doc?

    My XML document has this:
    <!DOCTYPE Users SYSTEM "Users.dtd" []>
    So the name of this document's type is "Users", i.e. it is a Users document. However, I cannot figure out how to get that during parsing! I have set the following (and implemented all the correct interfaces):
         pa.setContentHandler( userHandler );
         pa.setDTDHandler( userHandler );
         pa.setEntityResolver( userHandler );
         pa.setErrorHandler( userHandler );My userHandler object is of class: XMLUserHandler (I made it up) that extends DefaultHandler and implements:
    DTDHandler, EntityResolver, ErrorHandler, ContentHandler
    and overrides all the nec. methods.
    What am I missing? how do I get it to return "Users" from:
    <!DOCTYPE Users SYSTEM "Users.dtd" []>
    or if it was:
    <!DOCTYPE MyDumbName SYSTEM "Users.dtd" []>
    how can I get it to return "MyDumbName"?
    Thank you all for your help in advance!

    For anyone wondering, the answer is to use LexicalHandler. However, they made it "hidden" in the sense that setting this property is not as easy as setting the ContentHandler, for example. Also, not every implementation has to recognize the LexicalHandler. You do it this way:
    //MY CLASS THAT IMPLEMENTS LexicalHandler INTERFACE
    MyLexicalHandler myHandler = new MyLexicalHandler();
    myXMLReader.setProperty( "http://xml.org/sax/properties/lexical-handler", myHandler );then just call "parse()" and it will automatically call your lexical handler, assuming it implements that.
    The main method in LexicalHandler here (i.e. the one that handles what I was looking for) is:
    public void startDTD(String name, String publicId, String systemId) throws SAXException

  • Persisting unexplained errors when parsing XML with schema validation

    Hi,
    I am trying to parse an XML file including XML schema validation. When I validate my .xml and .xsd in NetBeans 5.5 beta, I get not error. When I parse my XML in Java, I systematically get the following errors no matter what I try:
    i) Document root element "SQL_STATEMENT_LIST", must match DOCTYPE root "null".
    ii) Document is invalid: no grammar found.
    The code I use is the following:
    try {
    Document document;
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(true);
    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    document = builder.parse( new File(PathToXml) );
    My XML is:
    <?xml version="1.0" encoding="UTF-8"?>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <!-- Defining the SQL_STATEMENT_LIST element -->
    <xs:element name="SQL_STATEMENT_LIST" type= "SQL_STATEMENT_ITEM"/>
    <xs:complexType name="SQL_STATEMENT_ITEM">
    <xs:sequence>
    <xs:element name="SQL_SCRIPT" minOccurs="0" maxOccurs="unbounded"/>
    </xs:sequence>
    </xs:complexType>
    <!-- Defining simple type ApplicationType with 3 possible values -->
    <xs:simpleType name="ApplicationType">
    <xs:restriction base="xs:string">
    <xs:enumeration value="DawningStreams"/>
    <xs:enumeration value="BaseResilience"/>
    <xs:enumeration value="BackBone"/>
    </xs:restriction>
    </xs:simpleType>
    <!-- Defining the SQL_SCRIPT element -->
    <xs:element name="SQL_SCRIPT" type= "SQL_STATEMENT"/>
    <xs:complexType name="SQL_STATEMENT">
    <xs:sequence>
    <xs:element name="NAME" type="xs:string"/>
    <xs:element name="TYPE" type="xs:string"/>
    <xs:element name="APPLICATION" type="ApplicationType"/>
    <xs:element name="SCRIPT" type="xs:string"/>
    <!-- Making sure the following element can occurs any number of times -->
    <xs:element name="FOLLOWS" type="xs:string" minOccurs="0" maxOccurs="unbounded"/>
    </xs:sequence>
    </xs:complexType>
    </xs:schema>
    and my XML is:
    <?xml version="1.0" encoding="UTF-8"?>
    <!--
    Document : SQLStatements.xml
    Created on : 1 juillet 2006, 15:08
    Author : J�r�me Verstrynge
    Description:
    Purpose of the document follows.
    -->
    <SQL_STATEMENT_LIST xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="http://www.dawningstreams.com/XML-Schemas/SQLStatements.xsd">
    <SQL_SCRIPT>
    <NAME>CREATE_PEERS_TABLE</NAME>
    <TYPE>CREATION</TYPE>
    <APPLICATION>DawningStreams</APPLICATION>
    <SCRIPT>
    CREATE CACHED TABLE PEERS (
    PEER_ID           VARCHAR(20) NOT NULL,
    PEER_KNOWN_AS      VARCHAR(30) DEFAULT ' ' ,
    PRIMARY KEY ( PEER_ID )
    </SCRIPT>
    </SQL_SCRIPT>
    <SQL_SCRIPT>
    <NAME>CREATE_COMMUNITIES_TABLE</NAME>
    <TYPE>CREATION</TYPE>
    <APPLICATION>DawningStreams</APPLICATION>
    <SCRIPT>
    CREATE CACHED TABLE COMMUNITIES (
    COMMUNITY_ID VARCHAR(20) NOT NULL,
    COMMUNITY_KNOWN_AS VARCHAR(25) DEFAULT ' ',
    PRIMARY KEY ( COMMUNITY_ID )
    </SCRIPT>
    </SQL_SCRIPT>
    <SQL_SCRIPT>
    <NAME>CREATE_COMMUNITY_MEMBERS_TABLE</NAME>
    <TYPE>CREATION</TYPE>
    <APPLICATION>DawningStreams</APPLICATION>
    <SCRIPT>
    CREATE CACHED TABLE COMMUNITY_MEMBERS (
    COMMUNITY_ID VARCHAR(20) NOT NULL,
    PEER_ID VARCHAR(20) NOT NULL,
    PRIMARY KEY ( COMMUNITY_ID, PEER_ID )
    </SCRIPT>
    </SQL_SCRIPT>
    <SQL_SCRIPT>
    <NAME>DROP_PEER_TABLE</NAME>
    <TYPE>DELETION</TYPE>
    <APPLICATION>DawningStreams</APPLICATION>
    <SCRIPT>
    DROP TABLE PEERS IF EXISTS
    </SCRIPT>
    </SQL_SCRIPT>
    <SQL_SCRIPT>
    <NAME>DROP_COMMUNITIES_TABLE</NAME>
    <TYPE>DELETION</TYPE>
    <APPLICATION>DawningStreams</APPLICATION>
    <SCRIPT>
    DROP TABLE COMMUNITIES IF EXISTS
    </SCRIPT>
    </SQL_SCRIPT>
    <SQL_SCRIPT>
    <NAME>DROP_COMMUNITY_MEMBERS_TABLE</NAME>
    <TYPE>DELETION</TYPE>
    <APPLICATION>DawningStreams</APPLICATION>
    <SCRIPT>
    DROP TABLE COMMUNITY_MEMBERS IF EXISTS
    </SCRIPT>
    </SQL_SCRIPT>
    <SQL_SCRIPT>
    <NAME>CREATE_COMMUNITY_MEMBERS_VIEW</NAME>
    <TYPE>CREATION</TYPE>
    <APPLICATION>DawningStreams</APPLICATION>
    <SCRIPT>
    CREATE VIEW COMMUNITY_MEMBERS_VW AS
    SELECT P.PEER_ID, P.PEER_KNOWN_AS, C.COMMUNITY_ID, C.COMMUNITY_KNOWN_AS
    FROM PEERS P, COMMUNITIES C, COMMUNITY_MEMBERS CM
    WHERE P.PEER_ID = CM.PEER_ID
    AND C.COMMUNITY_ID = CM.COMMUNITY_ID
    </SCRIPT>
    <FOLLOWS>CREATE_PEERS_TABLE</FOLLOWS>
    <FOLLOWS>CREATE_COMMUNITIES_TABLE</FOLLOWS>
    </SQL_SCRIPT>
    </SQL_STATEMENT_LIST>
    Any ideas? Thanks !!!
    J�r�me Verstrynge

    Hi,
    I found the solution in the following post:
    Validate xml with DOM - no grammar found
    Sep 17, 2003 10:58 AM
    The solution is to add a line of code when parsing:
    try {
    Document document;
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(true);
    factory.setNamespaceAware(true);
    factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema");
    DocumentBuilder builder = factory.newDocumentBuilder();
    document = builder.parse( new File(PathToXml) );
    The errors are gone !!!
    J�r�me Verstrynge

  • Flash Player 10 removes HTML encoding in CDATA when parsing XML

    I have an application that was written with Flash Professional 8/AS2 and it parses XML for rendering dynamic media content. The XML pulls text with HTML markup out of CDATA sections and places them into an html enabled text field. Everything has worked wonderfully until Flash Player 10.
    Now, if we use html escape characters for greater than or less than symbols, they are being decoded by the xml parser.
    Here's my example CDATA section:
    Here <u>we</u> go: This &#60;node&#62; &lt;works&gt; 
    when I grab its value using nodeValue or toString, the results are different from Flash Player 9 to 10. Here's what I'm getting:
    node.nodeValue (Flash Player 9):
    Here <u>we</u> go: This &#60;node&#62; <works>
    node.nodeValue (Flash Player 10):
    Here <u>we</u> go: This <node> <works>
    node.toString (Flash Player 9):
    Here <u>we</u> go: This &#60;node&#62; &lt;works&gt;
    node.toString (Flash Player 10):
    Here <u>we</u> go: This <node> <works>
    In Flash 10, if I escape the ampersand, it will work, but this doesn't work in 9. for example, the following works in 10:
    <![CDATA[Here <u>we</u> go: This &amp;#60;node&amp;#62; &amp;lt;works&amp;gt;]]>
    This all happens before I assign it to a text field. How do I keep the parser from destroying my escaped characters in Flash 10? Do I just need to drop support for Flash Player 9 and go for what works in 10, or is there a solution for both?
    Message was edited by: Xygar

    I'm not an action script programmer. I'm just trying to fix some code written like 3 years ago. So I think I am wrong about where this problem is coming from.
    The original developer actually set up a class to load a remote xml file via sendAndLoad on a LoadVars object. It passes an object with an onData delegate set that passes the event object to an xml parsing method.
    the parsing method looks like this:
         private function parseXml(eventObj:Object){
              if(eventObj != undefined)
                   try
                        //ExternalInterface.call("logMessage", eventObj.toString());
                        _xmlDoc.parseXML(eventObj.toString());
                        _xmlDoc.loaded = true;
                        _xmlDoc.onLoad(true);
                   catch(ex)
                        _xmlDoc.onLoad(false);
              else
                   _xmlDoc.onLoad(false);
    I added the ExternalInterface call so that I could log the stuff out in javascript (since I'm not sure how to debug this app).
    _xmlDoc is defined as: private var _xmlDoc:XML;
    The eventObj receives the xml string and then passes it to the parseXML thing. Here's the odd part. In Flash Player 10, if I comment out my ExternalInterface call, the xml string has the escaped character decoded before it gets to the parser.
    However, if I uncomment my ExternalInterface call, it logs the escaped strings as i would expect, but the parser gets the correct formatting this time! Suddenly it all works.
    I really wish I had an AS2 programmer on campus still....

  • Slow processing when Parsing  XML files

    Hi
    I have written a utility in Java (using JAXP) which parses an .xml file. This xml file
    contains references to n number of other xml files. From here I direct the parser to each of these individual xml files where it searches for elements with a particular tag name, lets say 'node'. As in,
    <node name= "Parent A">
    <entry key="type" value="car"/>....
    </node>
    <node name= "Parent B">
    <entry key="type" value="Truck"/>
    </node>
    I am collecting all the 'nodes' from these n xml files and then finally building a single xml file which will contain only the 'node' and its attribute 'name' value. As in,
    <node name="Parent A"/>
    <node name="Parent B"/>
    In most cases n is a number greater than 100. Each of these n xml file have LOC exceeding 2 to 3000.
    NOW the issue is, the xml parser takes more than an hr to go through just 10 - 15 xml files , collects the 'node', and building a new DOM object which I finally get published using Xml Transformer.
    In effect , it beats the whole purpose of writing this utility as no programmer will stick around for an hr to to watch it happen/finish.
    Apart from maybe further fine tuning my logic, which I've almost exhusted, is there any 'faster' way of doing the whole thing.
    Please reply. Any comment would be greatly appreciated.
    I am using JAXP 1.3 specs to parse and build the DOM.

    DOM is slow.
    Do it yourself using a simple SAX-parser. For all startElement - check if it is a "node", and then write your output!
    Xerces is faster than the built in Crimoson SAX-parser in Java.
    Parsing with Xerces a 2GHz machine takes manages about 5-6 MB/s of XML files.
    Or use STX with Joost - although it's not THAT much faster
    http://www.xml.com/pub/a/2003/02/26/stx.html
    http://joost.sourceforge.net/
    Gil

  • How to ignore white space when parse xml document using xerces 2.4.0

    When I run the program with the xml given below the following error comes.
    Problem parsing the file.java.lang.NullPointerExceptionjava.lang.NullPointerExce
    ption
    at SchemaTest.main(SchemaTest.java:25)
    ============================================================
    My expectation is "RECEIPT". Pls send me the solution.
    import org.apache.xerces.parsers.DOMParser;
    import org.xml.sax.InputSource;
    import java.io.*;
    import org.xml.sax.ErrorHandler;
    import org.w3c.dom.*;
    public class SchemaTest {
    public static void main (String args[])
    try
    FileInputStream is = new FileInputStream(new File("C:\\ADL\\imsmanifest.xml"));
    InputSource in = new InputSource(is);
    DOMParser parser = new DOMParser();
    //parser.setFeature("http://xml.org/sax/features/validation", false);
    //parser.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation", "memory.xsd");
    //ErrorHandler errors = new ErrorHandler();
    //parser.setErrorHandler(errors);
    parser.parse(in);
    Document manifest = parser.getDocument();
    manifest.normalize();
    NodeList nl = manifest.getElementsByTagName("organization");
    System.out.println((((nl.item(0)).getChildNodes()).item(0)).getFirstChild().getNodeValue());
    catch (Exception e)
    System.out.print("Problem parsing the file."+e.toString());
    e.printStackTrace();
    <?xml version = '1.0'?>
    <organizations default="detail">
    <organization identifier="detail" isvisible="true">
    <title>RECEIPT</title>
    <item identifier="S100000" identifierref="R100000" isvisible="true">
    <title>Basic Module</title>
    <item identifier="S100001" identifierref="R100001" isvisible="true">
    <title>Objectives</title>
    <metadata/>
    </item>
    </item>
    <metadata/>
    </organization>
    </organizations>
    Is there a white space problem? How do I get rid from this problem.

    ok now i really wrote the whole code, a bit scrolling in the API is to hard?
                DocumentBuilderFactory dbf = new DocumentBuilderFactory();
                DocumentBuilder db = dbf.newDocumentBuilder();
                dbf.setNamespaceAware(true); //or set false
                Document d = db.parse(inputstream);

  • Ignore DOCTYPE tag in xml

    Hi!,
    I need to remove DOCTYPE tag from the xml file. The parser is trying to validate the DTD. I do not want to validate, I just want to parse. I could not find any documentation on how this can be done. if any one of you have done this please let me know how you have managed to ignore the DOCTYPE tag.
    Regards

    Here is one way to do it:
    Example taglib DOCTYPE:
    <!DOCTYPE taglib
    PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
    "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
    Example Code:
    // Get your parser, then set its EntityResolver to your own custom er.
    parser.setEntityResolver(new EntityResolver()
    public InputSource resolveEntity(String publicId, String systemId)
    if ("-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN".equals(publicId))
    return new InputSource(
    new ByteArrayInputStream("<?xml version='1.0' encoding='UTF-8'?>".getBytes()));
    else
    return null;
    });

  • SAXNotRecognisedException when parsing XML

    Hi
    I have written the following code to verify my XML ( in String form) against xsd schema
    When i do setProperty for schemaLanguage or schemaLocation I get an SAXNotRecognisedException.
    Could someone please help me out with this !
    String schemaString = XMLSchemaGen.getInstance().generateSchema();
    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setNamespaceAware(true);
    spf.setValidating(true);
    DefaultHandler dh = new DefaultHandler();
    SAXParser sp = spf.newSAXParser();
    sp.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
    "http://www.w3.org/2001/XMLSchema");
    sp.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLocation",
    schemaString) ;
    Reader inputstream= new StringReader(XMLDocument);
    InputSource ips = new InputSource(inputstream);
    sp.parse(ips,dh);
    System.out.println("Successfully Parsed and Validated");
    Thanks

    I understand that, I can't figure out how it's poorly formed... I'm inexperienced with DTDs, tell me if you see a problem with this. It's to store accounts for a program:
    <?xml version="1.0" encoding="UTF-8"?>
    <!ELEMENT Accounts (Level, Level, Level)>
    <!ELEMENT Level (Account*)>
    <!ATTLIST Level type (admins | gmods | players) #REQUIRED>
    <!ELEMENT Account (String, int, int, EmailAddress, InetAddress?)>
    <!ATTLIST Account username ID #REQUIRED>
    <!ELEMENT String (#PCDATA)>
    <!ATTRIBUTE String name CDATA #REQUIRED>
    <!ELEMENT int (#PCDATA)>
    <!ATTLIST int name CDATA #REQUIRED>
    <!ELEMENT EmailAddress (#PCDATA)>
    <!ELEMENT InetAddress (#PCDATA)>
    <!ATTLIST InetAddress name CDATA #REQUIRED>

  • Ignore DOCTYPE tag in XML Validation

    All,
    I am trying to read an XML file using a file adapter with passing using the XSD created out of that XML. In normal scenario it works fines. Problems comes when I cam trying to read the XML file which had the Tag <!DOCTYPE> as shown below on top of the root node.
    In this case XML parsing is failing and file adapter is throwing the error.
    Any pointers on this.
    Many Thanks.
    Regards,
    Ramana.
    Sample XML (For Example):
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <!DOCTYPE CFXML [
    <!ELEMENT CFXML (thisDocumentGenerationDateTime,thisDocumentIdentifier,CFData)>
    <!ELEMENT thisDocumentGenerationDateTime (DateTimeStamp)>
    <!ELEMENT thisDocumentIdentifier (ProprietaryDocumentIdentifier)>
    <!ELEMENT CFData (ProprietaryInformation*,ProductLineItem+,CFReportBLOB?)>
    <!ELEMENT DateTimeStamp (#PCDATA)>
    <!ELEMENT ProprietaryDocumentIdentifier (#PCDATA)>
    <!ELEMENT ProprietaryInformation (Name,Value)>
    <!ELEMENT ProductLineItem ( ProductLineNumber , TransactionType , CPUSIUvalue , ConfigurationControlNumber?, ProprietaryGroupIdentifier , ServicePacLineNumberReference? , Quantity , ProductIdentification , UnitListPrice? , MaintenanceUnitListPrice? , ProductSubLineItem* ) >
    <!ELEMENT CFReportBLOB (#PCDATA)>
    <!ELEMENT Name (#PCDATA)>
    <!ELEMENT Value (#PCDATA)>
    <!ELEMENT CPUSIUvalue (#PCDATA)>
    <!ELEMENT ConfigurationControlNumber (#PCDATA)>
    <!ELEMENT ProductLineNumber (#PCDATA)>
    <!ELEMENT ProprietaryGroupIdentifier (#PCDATA)>
    <!ELEMENT ServicePacLineNumberReference (#PCDATA)>
    <!ELEMENT Quantity (#PCDATA)>
    <!ELEMENT TransactionType (#PCDATA)>
    <!ELEMENT ProductIdentification (PartnerProductIdentification*) >
    <!ELEMENT ProductSubLineItem ( LineNumber, TransactionType, Quantity , ExchangeAddSubLineItemNumber? , ProductIdentification, UnitListPrice?,MaintenanceUnitListPrice?)>
    <!ELEMENT UnitListPrice ( FinancialAmount, PriceTerm)>
    <!ELEMENT MaintenanceUnitListPrice (FinancialAmount, PriceTerm)>
    <!ELEMENT PartnerProductIdentification ( OrderedProductIdentifier?, ProprietaryProductIdentifier, ProductDescription?, ProductTypeCode?, ProductIdentifierTypeCode?) >
    <!ELEMENT LineNumber (#PCDATA)>
    <!ELEMENT ExchangeAddSubLineItemNumber (#PCDATA)>
    <!ELEMENT FinancialAmount ( GlobalCurrencyCode, MonetaryAmount )>
    <!ELEMENT PriceTerm (#PCDATA)>
    <!ELEMENT OrderedProductIdentifier (#PCDATA)>
    <!ELEMENT ProprietaryProductIdentifier (#PCDATA)>
    <!ELEMENT ProductDescription (#PCDATA)>
    <!ELEMENT ProductTypeCode (#PCDATA)>
    <!ELEMENT ProductIdentifierTypeCode (#PCDATA)>
    <!ELEMENT GlobalCurrencyCode (#PCDATA)>
    <!ELEMENT MonetaryAmount (#PCDATA)>
    ]>
    <CFXML>
    <thisDocumentGenerationDateTime>
    <DateTimeStamp>2008-05-23T14:02:49.465-05.00</DateTimeStamp>
    </thisDocumentGenerationDateTime>
    </CFXML>

    Guys,
    There is a small tricky point here. The above operation works in the simple file adapter but dosn't work for Chunk read file adapter.
    The InteractionSpec (oracle.tip.adapter.file.outbound.ChunkedInteractionSpec) of the Chunk read file adapter dosn't support this functionality. I guess we have raise an SR, if I am correct.
    -Ramana.

  • How to use responseXML to parse xml

    Hi,
    I am sending this xml from server
    <assignmentList>
    <assignment>
    <id>333</id><name>1170235257994</name><fileClass>4</fileClass><checked_out_by> </checked_out_by><status>s1</status><publication>p1</publication><section>s1</section><change_type>1</change_type><listenerClass>0</listenerClass>
    </assignment>
    <assignment>
    <id>333</id><name>1170235257994</name><fileClass>4</fileClass><checked_out_by> </checked_out_by><status>s1</status><publication>p1</publication><section>s1</section><change_type>1</change_type><listenerClass>1</listenerClass>
    </assignment>
    </assignmentList>
    I need to parse above xml to get id , name,fileclass etc
    but in my js
    var root = o.responseXML.documentElement;
    var length=root.getElementsByTagName('assignment").length;
    alert(length); // displays 0.
    I need to get the length and iterate to get values from above two tags.
    But could not achieve it.
    but when I send
    <assignmentList>
    <assignment>
    <id>333</id><name>1170235257994</name><fileClass>4</fileClass><checked_out_by> </checked_out_by><status>s1</status><publication>p1</publication><section>s1</section><change_type>1</change_type><listenerClass>0</listenerClass>
    </assignment>
    </assignmentList>
    alert(length); // displays 1. correct
    Can you please show me how I can get correct length and then get values from it
    by getting values I mean
    var assetId = root.getElementsByTagName('id').firstChild.nodeValue;
    currently not working.
    waiting for response
    thanks

    I have similar error
    my servlet writer.
    response.getWriter().write("<valid>pass</valid>");
            response.getWriter().write("<valid>fail</valid>");
            response.getWriter().write("<good>yes</good>");
            response.getWriter().write("<good>now</good>");
    javascript
    var msg = responseXML.getElementsByTagName("valid");
         document.getElementById('log').innerHTML  += "<br> " + msg + "....length=" + msg.length;
         for(i=0; i<msg.length; i++){
              document.getElementById('log').innerHTML  += "<br> " + msg.firstChild.nodeValue;
              var newOption = new Option(msg[i], "VALUE");
              document.inputForm.pendingMCObox.options[1] = newOption;
         msg = responseXML.getElementsByTagName("good");
         document.getElementById('log').innerHTML += "<br> " + msg + "....length=" + msg.length;
         for(i=0; i<msg.length; i++){
              document.getElementById('log').innerHTML += "<br> " + msg[i].firstChild.nodeValue;
              var newOption = new Option(msg[i], "VALUE");
              document.inputForm.pendingMCObox.options[1] = newOption;
    for some reasons, the length is 0.  What am i doing wrong here?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • How to specify delimiter when parsing the parameter list in URL

    Here is a sample URL used to call the servlet:
    http://myhost.com/servlet?param1=test1&param2=test2&param3=test3In the doGet method of my servlet, I understand I can use the getParameter method to retrieve the various parameter values:
    String p_param1 = request.getParameter("param1");
    String p_param2 = request.getParameter("param2");
    String p_param3 = request.getParameter("param3");However, what if the URL was of the form:
    http://myhost.com/servlet?param1=test1+param2=test2+param3=test3where the URL parameter delimiter was a plus sign rather than an ampersand (&).
    By default, the servlet is only recognizing the ampersand (&) as a parameter delimiter.
    When I use a plus sign as the delimiter, getParameter retrieves everything after the question mark (?) as the first parameter
    i.e. param1 = test1 param2=test2 param3=test3
    param2 = null
    param3 = null
    How can I get getParameter to recognize a plus sign (+) as a valid delimiter?

    Servlets follow the HTTP specification. So, there is not much you can do on that level. What you could do (though I do not recommend it) is to set-up a filter that will automatically swap the plus with an ampersand before the actual servlet processes it. My strong advice, however, is to give up on using a nonstandard delimiter.
    [http://java.sun.com/products/servlet/Filters.html]
    - Saish

  • Xmlparser.parse fails when parsing xml with dtd

    Has anybody used successfully called xmlparser.parse in PL/SQL
    to parse an xml file with a dtd? When I try I get the following
    error:
    ERROR at line 1:
    ORA-20100: Error occurred while parsing: Invalid argument
    ORA-06512: at "SYS.XMLPARSER", line 22
    ORA-06512: at "SYS.XMLPARSER", line 69
    ORA-06512: at line 6
    When I remove the dtd reference from the xml file it works.
    (I posted this question yesterday but no responses, so I'm
    trying again...)
    Thanks - Dana

    Please see:
    http://forums.oracle.com/forums/message.jsp?id=617954
    for the solution. Thanks.

  • How do switches work when launching a java app

    Hi,
    How do I use a "switch" in the launch command for an app. ie
    java -cp myclassPath -mySwitch hello MyClass arg1 arg2
    I want the app to do something depending on the presence of and the value of the switch "mySwitch". I know I can pass in args and work with these but I want to have control via the use of this optional switch.
    PS when I google for "java switch" or search this forum for it I only get stuff on the switch statement so I don't know if what I'm trying to do is even possible.

    Read the documentation for java command. Especially, look at the -D option.

Maybe you are looking for

  • PI 7.0 problem

    Hello All, We are trying to install PI 7.0 but we have doubt. In PI 7.0 is it required to work in the default client or we can also create some cleints? iF so How can we do that?If not, can i work in the default client ? Regards

  • Double Space a String?

    I need to make a void method for school, that will take text, I asume in the form of a String, and print it double spaced, like Microsoft Word. My teacher told me that the method would only be one line of code. HOW DO I DO THIS?

  • Signing with Smart Card (PKCS#11)

    I'm trying to sign my .jar with ActivCard smart card and jarsigner.exe, but I got NullPointerException. I have succeeded to get list of certificates present on smart card. Is there better PKCS#11 provider then sun.security.pkcs11.SunPKCS11?

  • How to make Bluetooth keyboard work?

    Firstly, I have spent over an hour reading this, that and the other. Nothing seems to make it work. It did work. For a while. Now it just seems to spontaneously decide to stop accepting input. Or sending keys. Or whatever the issue is. 0. The batteri

  • BAPI_PO_CREATE1 Special Characters ?

    Hi, I am using BABI_PO_CREATE1 for Purchase Order creation via Web Dynpro Application.  For some reason the Potextheader field Text_Line is inserting a '#' character in the print preview for the PO when the text was submitted with carriage returns fr