NEED HELP:To Parse Conditional Operator Within An Expression.

Hi there:
I'm having some difficulties to parse some conditoional operator. My requirements is:
Constants value: int a=1,b=2,c=3
Input/Given value: 2
conditional operator expression: d=a|b|c
Expected result: d=true
Summary: I like to receive a boolean from anys expressions defined, which check against Input/Given value.Note: The expression are various from time to time, based on user's setup, the method is smart enough to return boolean based on any expression.
Let me know if you have any concerns.
Thanks a million,
selena

here is a simple example.
BNF changes
EXPR ::= OPERATOR
EXPR ::= OPERATION OPERANT EXPR
This is as far as I can go, please use it as a template only
because you need to take into account the precedence using ()
the logic of the eval was simply right to left so I think it is not what you want
Cheers
public interface Expression
     String OR = "|";
     String AND = "&";
     public boolean eval(int value) throws Exception;
public class ExpressionImpl implements Expression
     public String oper1;
     public String operant;
     public Expression tail;
     /* (non-Javadoc)
      * @see parser.Expression#eval()
     public boolean eval(int value) throws Exception
          int val1 = getValue(oper1);
          if (null == tail)
System.out.println(val1 + ":" + value);               
               return (val1 == value);
          else
               if (OR.equals(operant))
                    return (val1 == value || tail.eval(value));
               else if (AND.equals(operant))
                    return (val1 == value && tail.eval(value));
               else
                    throw new Exception("unsupported operant " + operant);
     private int getValue(String operator) throws Exception
          Integer temp = ((Integer)Parser.symbol_table.get(operator));
          if (null == temp)
               throw new Exception("symbol not found " + operator);
          return temp.intValue();
     public String toString()
          if (null == operant) return oper1;
          return oper1 + operant + tail.toString();
public class Parser
     public static HashMap symbol_table = new HashMap();
      * recursive parsing
     public Expression parse(String s)
          ExpressionImpl e = new ExpressionImpl();
          e.oper1 = String.valueOf(s.charAt(0));
          if (s.length() == 1)
               return e;
          else if (s.length() > 2)
               e.operant = String.valueOf(s.charAt(1));
               e.tail = parse(s.substring(2));
          else
               throw new IllegalArgumentException("invalid input " + s);
          return e;
     public static void main(String[] args) throws Exception
          Parser p = new Parser();
          Parser.symbol_table.put("a", new Integer(1));
          Parser.symbol_table.put("b", new Integer(2));
          Parser.symbol_table.put("c", new Integer(3));
          Parser.symbol_table.put("d", new Integer(4));
          Expression e = p.parse("a|b|c&d");
          System.out.println("input " + e.toString());
          System.out.println(e.eval(2));
}

Similar Messages

  • Urgent : Need help in parsing XML from Sharepoint and save it into DB

    Hi ,
    I am Sharepoint guy and a newbie in Oracle . PL/SQL
    I am using UTL_DBWS Package to call a Sharepoint WebService " and was sucessfull , Now the xml has to be parsed and stored into a Table. I am facing the issue as the XML has a different namesoace and normal XPATH query is not working
    Below is the XML and need help in parsing it
    declare
    responsexml sys.XMLTYPE;
    testparsexml sys.XMLTYPE;
    begin
    responsexml := sys.XMLTYPE('<GetListItemsResponse xmlns="http://schemas.microsoft.com/sharepoint/soap/">
    <GetListItemsResult>
    <listitems xmlns:s="uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882" xmlns:dt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882" xmlns:rs="urn:schemas-microsoft-com:rowset" xmlns:z="#RowsetSchema">
    <rs:data ItemCount="2">
    <z:row ows_MetaInfo="1;#" ows__ModerationStatus="0" ows__Level="1" ows_Title="Test Title 1" ows_ID="1" ows_owshiddenversion="1" ows_UniqueId="1;#{9C45D54E-150E-4509-B59A-DB5A1B97E034}" ows_FSObjType="1;#0" ows_Created="2009-09-12 17:13:16" ows_FileRef="1;#Lists/Tasks/1_.000"/>
    <z:row ows_MetaInfo="2;#" ows__ModerationStatus="0" ows__Level="1" ows_Title="Testing Tasks" ows_ID="2" ows_owshiddenversion="1" ows_UniqueId="2;#{8942E211-460B-422A-B1AD-1347F062114A}" ows_FSObjType="2;#0" ows_Created="2010-02-14 16:44:40" ows_FileRef="2;#Lists/Tasks/2_.000"/>
    </rs:data>
    </listitems>
    </GetListItemsResult>
    </GetListItemsResponse>');
    testparsexml := responsexml.extract('/GetListItemsResponse/GetListItemsResult/listitems/rs:data/z:row/@ows_Title');
    DBMS_OUTPUT.PUT_LINE(testparsexml.extract('/').getstringval());
    end;
    The issue is with rs:data , z:row nodes.... please suggest how to handle these kind of namespaces in Oracle
    I need the parse the attribute "ows_Title" and save it into a DB
    this script would generate "Error occured in XML Parsing"
    Help is appriciated, thanks for looking

    SQL> SELECT *
      FROM XMLTABLE (
              xmlnamespaces ('http://schemas.microsoft.com/sharepoint/soap/' as "soap",
                             '#RowsetSchema' AS "z"
              'for $i in //soap:*//z:row return $i'
              PASSING xmltype (
                         '<GetListItemsResponse xmlns="http://schemas.microsoft.com/sharepoint/soap/">
    <GetListItemsResult>
    <listitems xmlns:s="uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882" xmlns:dt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882" xmlns:rs="urn:schemas-microsoft-com:rowset" xmlns:z="#RowsetSchema">
    <rs:data ItemCount="2">
    <z:row ows_MetaInfo="1;#" ows__ModerationStatus="0" ows__Level="1" ows_Title="Test Title 1" ows_ID="1" ows_owshiddenversion="1" ows_UniqueId="1;#{9C45D54E-150E-4509-B59A-DB5A1B97E034}" ows_FSObjType="1;#0" ows_Created="2009-09-12 17:13:16" ows_FileRef="1;#Lists/Tasks/1_.000"/>
    <z:row ows_MetaInfo="2;#" ows__ModerationStatus="0" ows__Level="1" ows_Title="Testing Tasks" ows_ID="2" ows_owshiddenversion="1" ows_UniqueId="2;#{8942E211-460B-422A-B1AD-1347F062114A}" ows_FSObjType="2;#0" ows_Created="2010-02-14 16:44:40" ows_FileRef="2;#Lists/Tasks/2_.000"/>
    </rs:data>
    </listitems>
    </GetListItemsResult>
    </GetListItemsResponse>')
    columns ows_MetaInfo varchar2(20) path '@ows_MetaInfo',
             ows_Title varchar2(20) path '@ows_Title',
             ows__ModerationStatus varchar2(20) path '@ows__ModerationStatus'
    OWS_METAINFO         OWS_TITLE            OWS__MODERATIONSTATUS
    1;#                  Test Title 1         0                   
    2;#                  Testing Tasks        0                   
    2 rows selected.

  • Urgently  need help for parsing IP header

    Hi, could anyone tell which class I should use to parsing the IP header of a packet?
    Thanks many many times!

    > Hi, could anyone tell which class I should use to
    parsing the IP header of a packet?
    DatagramPacket?
    > Urgently need help for parsing IP header
    Don't flag your question as urgent, even if it is for you.
    * We all answer questions here voluntarily, in our leisure time. We do that because doing so is fun for us, because we enjoy helping people and having interesting discussions. Guess what, it is much less fun if it gets stressful. So the last thing you want to do to get us to answer your question is to pass your stress over to us.
    * People who are stressed and want a fast answer often don't even find the time to do the necessary research or to formulate their question in an easy to comprehend way. That's even less fun to work with. So you really don't want us to feel your stress. Instead you want to take your time to write a well formulated post that is fun to answer. The less likely it is for us to know that your question is urgent, the more likely you are to get a fast answer!
    * The simple notion that you want your post to be answered faster than those of the other members might feel rather unfair to some of us. Doubly so because often "urgent" questions actually are homework questions. Yours might be different, but someone who had bad experiences with this type of question might not read far enough to notice.

  • I need help with the conditional build tag option RoboHelp 10

    I need help with the conditional build tag option. I want to apply CBT to content in a topic. I looked at the Help topics and believed that I applied the feature correctly. Howver, it is not working as desired. In the 2nd sentence below I want the text highlighted in blue to only appear for the printed output and the text printed in purple to only appear for the .htm /online output. Please help.
    There are common tasks used to manage the folders in the Navigator and the folders
    in the BBS Folders Viewer Grid. For more information on these common tasks see Help
    and Support in Success Enterprise. click the links below.

    Hi there
    Using tagging is a two part process.
    Part One
    You create and apply the tags to the information you wish to control.
    Part Two
    You create a Build Expression that is used when you generate your output. The Build Expression typically reads something like: NOT Tag1 (or whatever your tag name is)
    Then when you generate and use the Build Expression, the information tagged is not included in the build.
    Cheers... Rick

  • Need Help with parsing text

    Hello all, I hope this is an easy question....
    I have a string similar to
    <li><span class="RandomInformation">the latest news on my site</span></li>
    I am currently geting a string where each new line is a new <li> from a pure http call. what I need to do is split this down into an array of strings (Yes this is my website, and no im not trying to rebrand other's work...:) ) delimeted on :
    - each line needs to be a separate element within a multidimensional array
    - Can't split on CrLf because further up and further down I have other entries I dont care about, so I need to use the <li></li> as indicators that they contain the information I want.
    - out of each line, I need to separate them into multiple 'columns' within the array
    - one for the contents of the span clas (in this case "RandomInformation"
    - one element for the contents of the link (in this case my url, http://www.w2gas.com, but will be sub pages later like http://www.w2gas.com/page2.html)
    - most importantly one element for the text between anchor tags (this case it is "the latest news on my site")
    I tried a Regex for stripping the HTML tags out, however all I was left with was the text between anchors. I know I could do it based on character by character looping (have done that) but its terrible slow. I know there must be a way to accomplish this, however Im just too new to figure it out. (maybe?)
    Thanks in advance
    Lee

    Would something like [this |http://htmlparser.sourceforge.net/] help?

  • Need help msi 945pl neo crashed within 3 months use

    need help. my mobo doesnot start, no post, no beep. 
    1.main board 945pl neo(MS-7236)
    2.video card: msi RX300HM TD128E
    3.CPU Type: pentium 4 3Ghz (531)
    4.Memory Type:512mb ddr2 533 kingston
    5.Power Supply Type:generic 500W
    6.Operating System:windows xp
    Just a bit of history, when i first bought and assembled the unit(brand new) it was working fine for about 5 times used, then the next time i used a message window appear informing "a problem has been detected and window has been shut down
    to prevent damage" and before i can restart my unit i have to reset first the bios.. i encounter the same problem about 3 times..
    Then just about a week ago (about 3 months after i bought it)while working on a MSWORD only the same message appear with additional info which state that :
    1... be sure to if uhave adequate space... try changing video adapters
    2. check your hardware vendor for any bios updates.....
    3. tech/info
    stop 0X0000008E(0XC0000005, 0XBF87C5C8, 0XF8834C80, 0X00000000
    win32k-sys- add BF87C5C8 base at BF8000001,
    date stamp 41107F79
    then a blue screen appear
    which has an info of:
    Beginning dump of physical memory
    Physiscal memory dump complete
    Contact your system admin. or tech support group
     since then i cannot open my computer, there is NO Beep sound, no post, but the power Led is on and the HDD led goes On for the moment then goes out... same with the cdrom drive its spin for a moment, i can feel also the harddisk is spinning.
    i check the power supply, memory. video cards and harddisk with another computer(mobo) and its working just fine which led me to the conclusion that it is my MOBO that has the problem. Can this problem associated with the Bios (by the way i never update my bios and my computer is not connected to the net). What should i do?? What is the possible cause of this problem??

    Quote from: Hans on 24-January-07, 17:45:18
    Hi!
    This stop error can have more then one cause.
    Please view the microsoft knowledge base for more info, like this article:
    - http://support.microsoft.com/kb/834450
    Your specific error code is not in the base, but you can try searching for "stop 0X0000008E in win32k.sys".
    Start by clearing CMOS using the jumper or reset button on your board. Please disconnect your pc from AC power first.
    Please make sure that Service Pack 2 for Windows XP is installed on your system. If not, install it (if possible of course).
    Please check your memory using Memtest86 .
    Please try booting from CD or from diskette (the memtest diskette is bootable by itself).
    If the system will not boot after you tried this, please try starting barebone:
    - Take out all your hardware, including the mainboard and lay it on a piece of cardboard;
    - Leave the CPU where it is;
    - Install only one dimm, your videocard and one hard disk (and your power supply) and try to start the system. You can use a flat screwdriver to connect the two power pins that normally go to your power switch.
    If the system still will not boot, try another video card.
    hello!
    i'll already tried the list you suggested, and still nothing happened, again there are no beep, no post. only the power  led that lit and the fan that is spinning. reinstalling the OS seem impossible coz its not even booting... i'll test all my other hardware with another computer and they are working well...

  • Need help with Math related operations...

    I'm learning JAVA for more than 3 weeks and I really need help...
    I'm using SDK1.4 with Elixir IDE Lite (+patch installed).
    In the following screenshot <http://www.geocities.com/jonny_fyy/pics/java1.png>, I've got this error (when I right-click -> Compile) . Do you know what it means & how can I solve it?
    Here's how it should look if correct (pic scan from lab worksheet)... <http://www.geocities.com/jonny_fyy/pics/lab.jpg>
    Here's my java file... <http://www.geocities.com/jonny_fyy/FahToCeltxt.java>
    Thanks for helping :>

    Hi jonny
    One step ahead:
    import java.awt.*;
    import java.applet.*;
    import java.awt.event.*;
    public class FahToCeltxt extends Applet implements ActionListener {
         TextField msgField ;
         String msg = null;
         int msgValue;
         Label title;
         Button b;
         public void init() {
              title = new Label("Enter degrees in Fahrenheit: ");
              add(title);
              msgField = new TextField (10);
              add(msgField);
    //          msgField.addTextListener(this);
              b = new Button("Convert");
              b.addActionListener(this);
              add(b);
    //     public void textValueChanged(TextEvent event) {
    //          msgValue = Integer.parseInt(msgField.getText());
    //          repaint();
         public void paint (Graphics g) {
              int result = (msgValue - 32) * 5/9 ;
              g.drawString("Degree Centigrade is " + result , 50, 50);
      public void actionPerformed(ActionEvent e) {
              msgValue = Integer.parseInt(msgField.getText());
              repaint();
    }Regards.

  • Need help in using a case statement in expression operator

    Hi All,
    I am using OWB version 10.2.0.1.0.
    My requirement is to add a new column called call _zone_key in expression operator and map it to the target table. I need to use the below expression for populating call_zone_key values
    Expression:
    case when (INGRP1.CHARGETYPE in ('O','F') or  INGRP1.TARIFF_GROUP in ('SMSINT','MMSINT')or ( INGRP1.CALL_TYPE = '002' and   INGRP1.TARIFF_GROUP  = 'MTV'))
    then
    (select call_zone_reltn_key from call_zone_reltn where
    call_zone_cd=substr(case
      when substr( INGRP1.B_SUBNO,1,2)='00'
      then
      substr( INGRP1.B_SUBNO,3)
      else substr( INGRP1.B_SUBNO,1)
      end,1,length(call_zone_cd))and rownum=1)
    else -1
    end
    All the columns needed for using the above expression is available in INGRP1 but still I am unable to deploy the mapping using above expression. Call_zone_reltn table is also imported to the module. I am getting below error
    Error:
    Warning
    ORA-06550: line 4980, column 2:
    PLS-00103: Encountered the symbol "SELECT" when expecting one of the following:
       ( - + case mod new not null others <an identifier>
       <a double-quoted delimited-identifier> <a bind variable> avg
       count current exists max min prior sql stddev sum variance
       execute forall merge time timestamp interval date
       <a string literal with character set specification>
       <a number> <a single-quoted SQL string> pipe
       <an alternatively-quoted string literal with character set specification>
       <an alternativ
    NEW_MOD_MAP_CELL_USAGE_FCT_PRE
    Create
    Warning
    ORA-06550: line 4989, column 43:
    PLS-00103: Encountered the symbol ")" when expecting one of the following:
       * & - + ; / at for mod remainder rem <an exponent (**)> and
       or group having intersect minus order start union where
       connect || multiset
    If i replace the expression with numbers such as 1 or 2, I am able to deploy the mapping.
    Kindly help in fixing this issue.
    Thanks,
    Kabilan

    You can't use the SELECT statement inside the expression, you need to join both tables before the expression. Use a Join operator with this JOIN condition:
    CALCULATED_CALL_ZONE_CD = call_zone_reltn.call_zone_cd ( + )
    Where Calculated_call_zone_cd proceed from a previous expression:
    CALCULATED_CALL_ZONE_CD = substr(case when substr( INGRP1.B_SUBNO,1,2)='00' then substr( INGRP1.B_SUBNO,3) else substr( INGRP1.B_SUBNO,1) end,1,length(call_zone_cd))
    And after joining both tables, you can use another expression to get the rownum, then another filter operator to keep only the rownum = 1, and now you can use your expression without the SELECT, using the call_zone_cd column from the outgroup in the joiner operator (you need to include that column in the filter operator to use it).
    Regards
    ANA GH

  • Need help in displaying a feed within my flex app

    Hello guys,
    I was hoping that someone can push me in the right direction. I am looking to display our feed within our Flex Application. I am using some of the sample from tour de flex
    This is what I have so far:
    <?xml version="1.0" encoding="utf-8"?>
    <s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
         xmlns:s="library://ns.adobe.com/flex/spark"
         xmlns:mx="library://ns.adobe.com/flex/mx"
         width="960" height="850">
         <fx:Script>
         <![CDATA[
              import flashx.textLayout.conversion.TextConverter;
              import flashx.textLayout.elements.TextFlow;
              import spark.utils.TextFlowUtil;
              XML.ignoreWhitespace = false;
         ]]>
         </fx:Script>
         <fx:Style>
              @namespace s "library://ns.adobe.com/flex/spark";
              @namespace mx "library://ns.adobe.com/flex/mx";
              @namespace components "components.*";
              s|WindowedApplication {
                   background-color:#000000;
                   background-alpha:"0.9";
              s|ButtonBar s|ButtonBarButton:upAndSelected,
              s|ButtonBar s|ButtonBarButton:overAndSelected,
              s|ButtonBar s|ButtonBarButton:downAndSelected,
              s|ButtonBar s|ButtonBarButton:disabledAndSelected {
                   chromeColor: #00529c;
                   color: #FFFFFF;
              s|ButtonBar {
                   chromeColor: #053867;
                   color: #FFFFFF;
         </fx:Style>
         <fx:Declarations>
              <!-- Place non-visual elements (e.g., services, value objects) here -->
              <!--<s:HTTPService id="srv" url="http://feeds.feedburner.com/standforisrael/iWIn?format=xml" />-->
              <fx:XML id="srv" source="http://feeds.feedburner.com/standforisrael/iWIn?format=xml" />
         </fx:Declarations>
         <s:ButtonBar dataProvider="{myViewStack}" y="175" height="35" width="700" />
         <mx:ViewStack id="myViewStack" borderStyle="none" x="0" y="209" width="700" height="500">
              <s:NavigatorContent id="home" label="Home">
              </s:NavigatorContent>
              <s:NavigatorContent id="about" label="About Us">
              </s:NavigatorContent>
              <s:NavigatorContent id="rabbi" label="Rabbi Eckstein">
              </s:NavigatorContent>
              <s:NavigatorContent id="rabbiCom" label="Rabbi's Commentary">
              </s:NavigatorContent>
              <s:NavigatorContent id="programs" label="Our Blog">
                   <s:RichText id="rt5" width="280"
                        textFlow="{TextFlowUtil.importFromXML(srv)}" />
              </s:NavigatorContent>
         </mx:ViewStack>
    </s:WindowedApplication>
    Now when I run this I get a prompt that is telling me that if the program is already running to stop the program... I have no idea what program it is that i'm running that would prompt that type of dialogue box.
    I also get these errors:
    Unexpected processing instruction encountered and will be ignored. Found: type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css" IFCJ.mxml /IFCJ/src Unknown Flex Problem
    Unexpected processing instruction encountered and will be ignored. Found: type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl" IFCJ.mxml /IFCJ/src Unknown Flex Problem
    Is there anything that I am not doing right here?
    Any help would really be appreciated,
    Thank You

    I did try HTTPService but the problem that I was seeing was that I would need to push the information into a datagrid and that really doesn't help me witth presentation of the blog posts.
    What if I create a custom component that takes the RSS feed and parses it into sections like so:
    Title
    Description
    Link
    Where lets say the title is like so:
    [Bindable]
                public var title:String; <-- this is where I get stuck
    <s:Label x="0" y="80"
            text="{title}"/>
    I would like to also have that title wrapped in a url so that when the person is looking at our RSS they can click either the title or the read more link
    What else can i do?

  • Need help in parsing a VARCHAR2(4000 BYTES) field

    Hi Guys,
    Let me give the DB information first:
    SQL> select * from v$version;
    BANNER
    Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - 64bi
    PL/SQL Release 10.2.0.4.0 - Production
    CORE 10.2.0.4.0 Production
    TNS for Solaris: Version 10.2.0.4.0 - Production
    NLSRTL Version 10.2.0.4.0 - Production
    My problem is: The frontend of the application sends a large string into the VARCHAR2 (4000 BYTES) field. The string it sends is somewhat like this -
    <strong>Crit:</strong> Some text. <br><strong>Distinguished</strong> (points 3):Some comment text1. <blockquote> </blockquote><strong>Crit:</strong> Some other text.<br><strong>Distinguished</strong> (points 3):Some comment text2. <blockquote> </blockquote><strong>Crit:</strong> Some more text. <br><strong>Distinguished</strong> (points 3):Some comment text3. <blockquote> </blockquote><strong>Overall comments:</strong><br> Final text!!I want to parse the text and put into separate columns. Number of Crit: can be more than 3; its 3 up there. But the basic structure is same. What is the best possible way of parsing this in PL/SQL code? I want something like
    Table 1
    Crit                       Points           Comment
    Some text                3        Some comment text1.
    Some other text        3        Some comment text2.
    Some more text        3        Some comment text3.
    Table 2
    Overall comments
    Final text!!Please let me know, if you need further information.
    Thanks.
    Edited by: 794684 on Sep 14, 2010 4:15 AM
    Edited by: 794684 on Sep 14, 2010 4:38 AM
    Edited by: 794684 on Sep 14, 2010 4:53 AM
    Edited by: 794684 on Sep 14, 2010 6:42 AM

    Welcome to the forum.
    Looks like noformat tags are not working.Please use the {noformat}{noformat} tag if you want to post formatted examples/code.
    For example, when you type:
    {noformat}select *
    from dual;
    {noformat}
    it will appear as:select *
    from dual;
    when you post it on this forum...
    The FAQ will explain the other options you have: http://forums.oracle.com/forums/help.jspa                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Need help to parse a blob

    I'm trying to write an app to parse unified patch files. I've got a table to hold a set of patches from a single patch file and a table to hold each individual patch within the patch file (a single patch file can patch multiple source files). I'm currently holding the file contents in a blob field. I know how I would do this in python or other scripting languages, but I'm a complete pl/sql n00b, so I'm a bit clueless. Basically, I have the appropriate algorithm for parsing the file, but just not how to do it.
    Does anyone know of a tutorial that explains how to do this? Or maybe post some tips as to what pl/sql modules to look into?

    Kindly go through the following links ->
    http://www.oracle.com/technology/sample_code/tech/windows/odpnet/howto/anonyblock/index.html
    http://www.oracle.com/technology/sample_code/tech/java/jsp/samples/blob/blob.html
    http://www.psoug.org/reference/dbms_lob.html
    Might be helpful for you.
    Regards.
    Satyaki De.

  • Need help on parsing xml file...

    Hi all,
    I need to collect some data from an Xml file using java. I have the following code with me but I am unable to get the required result. I am unable to get the data from the tags belonging to the header and footer elements. Please find the code and the sample xml file below.
    Program to parse XML:
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.NodeList;
    import org.xml.sax.SAXException;
    public class JobLogDetails3{
         //No generics
         List myJobs;
         Document dom;
         public JobLogDetails3(){
              //create a list to hold the job objects
              myJobs = new ArrayList();
         public void runJobDetails() {
              //parse the xml file and get the dom object
              parseXmlFile();
              //get each joblog element and create a job object
              parseDocument();
              //Iterate through the list and print the data
              printData();
         private void parseXmlFile(){
              //get the factory
              DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
              try {
                   //Using factory get an instance of document builder
                   DocumentBuilder db = dbf.newDocumentBuilder();
                   //parse using builder to get DOM representation of the XML file
                   dom = db.parse("test.xml");
              }catch(ParserConfigurationException pce) {
                   pce.printStackTrace();
              }catch(SAXException se) {
                   se.printStackTrace();
              }catch(IOException ioe) {
                   ioe.printStackTrace();
         private void parseDocument(){
              //get the root elememt
              Element docEle = dom.getDocumentElement();
              //get a nodelist of <joblog> elements
              NodeList nl = dom.getElementsByTagName("*");
              if(nl != null && nl.getLength() > 0) {
                   for(int i = 0 ; i < nl.getLength();i++) {
                        //get the joblog element
                        Element el = (Element)nl.item(i);
                        //get the joblog object
                        Job J = getJob(el);
                        //add it to list
                        myJobs.add(J);
         * I take an joblog element and read the values in, create
         * an joblog object and return it
         * @param JobEl
         * @return
         private Job getJob(Element JobEl) {
              //for each <joblog> element get text or int values of
              //name ,id, age and name
              String jobServer = getTextValue(JobEl,"server");
              String jobName = getTextValue(JobEl,"name");
              String jobClient = getTextValue(JobEl,"machine_name");
              String jobStart = getTextValue(JobEl,"start_time");
              String jobType = getTextValue(JobEl,"type");
              String jobEnd = getTextValue(JobEl,"end_time");
              String jobSize = getTextValue(JobEl,"new_processed_bytes");
              //Create a new Job with the value read from the xml nodes
              Job J = new Job(jobServer,jobName,jobClient,jobStart,jobType,jobEnd,jobSize);
              return J;
         * I take a xml element and the tag name, look for the tag and get
         * the text content
         * i.e for <employee><name>John</name></employee> xml snippet if
         * the Element points to employee node and tagName is name I will return John
         * @param ele
         * @param tagName
         * @return
         private String getTextValue(Element ele, String tagName) {
              String textVal = null;
              NodeList nl = ele.getElementsByTagName(tagName);
              if(nl != null && nl.getLength() > 0) {
                   Element el = (Element)nl.item(0);
                   textVal = el.getFirstChild().getNodeValue();
              return textVal;
         * Calls getTextValue and returns a int value
         * @param ele
         * @param tagName
         * @return
         private int getIntValue(Element ele, String tagName) {
              //in production application you would catch the exception
              return Integer.parseInt(getTextValue(ele,tagName));
         * Iterate through the list and print the
         * content to console
         private void printData(){
              System.out.println("No of Jobs '" + myJobs.size() + "'.");
              Iterator it = myJobs.iterator();
              while(it.hasNext()) {
                   System.out.println(it.next().toString());
         public static void main(String[] args){
              //create an instance
              JobLogDetails JLD = new JobLogDetails();
              //call run example
              JLD.runJobDetails();
    Job Class
    public class Job {
         private String jobServer;
    private String jobName;
    private String jobClient;
    private String jobStart;
    private String jobType;
    private String jobEnd;
    private String jobSize;
         public Job(){
         public Job(String jobServer,String jobName,String jobClient,String jobStart,String jobType,String jobEnd,String jobSize ) {
              this.jobServer = jobServer;
              this.jobName = jobName;
              this.jobClient = jobClient;
    this.jobStart = jobStart;
              this.jobType = jobType;
    this.jobEnd = jobEnd;
    this.jobSize = jobSize;
         public String getjobServer() {
              return jobServer;
         public void setjobServer(String jobServer) {
              this.jobServer = jobServer;
         public String getjobName() {
              return jobName;
         public void setjobname(String jobName) {
              this.jobName = jobName;
         public String getjobClient() {
              return jobClient;
         public void setjobClient(String jobClient) {
              this.jobClient = jobClient;
    public String getjobStart() {
              return jobStart;
         public void setjobStart(String jobStart) {
              this.jobStart = jobStart;
    public String getjobType() {
              return jobType;
         public void setjobType(String jobType) {
              this.jobType = jobType;
    public String getjobEnd() {
              return jobEnd;
         public void setjobEnd(String jobEnd) {
              this.jobEnd = jobEnd;
    public String getjobSize() {
              return jobSize;
         public void setjobSize(String jobSize) {
              this.jobSize = jobSize;
         public String toString() {
              StringBuffer sb = new StringBuffer();
    sb.append(getjobServer());
              sb.append(",");
    sb.append(getjobName());
              sb.append(",");
              sb.append(getjobClient());
              sb.append(",");
              sb.append(getjobType());
              sb.append(",");
              sb.append(getjobStart());
              sb.append(",");
              sb.append(getjobEnd());
              sb.append(",");
              sb.append(getjobSize());
              sb.append(",");
              return sb.toString();
    Sample XML File:
    <?xml version="1.0" encoding="UTF-16" ?>
    - <joblog>
    <job_log_version version="2.0" />
    - <header>
    <filler>======================================================================</filler>
    <server>Job server: TGBBAK</server>
    <name>Job name: TGBSAP4-SQL-SQL DB Servers S2T - High-Weekly Full Backup</name>
    <start_time>Job started: 26 September 2011 at 01:00:04</start_time>
    <type>Job type: Backup</type>
    <log_name>Job Log: GFD_TGBBAK_71887.xml</log_name>
    <filler>======================================================================</filler>
    </header>
    <media_mount_date>Drive and media mount requested: 26/09/2011 01:00:04</media_mount_date>
    - <media_drive_and_media_info>
    <media_mount_date>Drive and media information from media mount: 26/09/2011 01:00:39</media_mount_date>
    <robotic_library_name>Robotic Library Name: HP 1</robotic_library_name>
    <drive_name>Drive Name: LTO4_2</drive_name>
    <slot>Slot: 43</slot>
    <media_label>Media Label: 000059L</media_label>
    <media_guid>Media GUID: {a6ca0062-7a6f-4b4b-8144-732ca25f2f9d}</media_guid>
    <media_overwrite_date>Overwrite Protected Until: 25/10/2011 19:24:58</media_overwrite_date>
    <media_append_date>Appendable Until: 02/10/2011 14:00:30</media_append_date>
    <media_set_target>Targeted Media Set Name: Weekly Tape</media_set_target>
    </media_drive_and_media_info>
    - <backup>
    <filler>======================================================================</filler>
    <title>Job Operation - Backup</title>
    <append_or_overwrite>Media operation - append.</append_or_overwrite>
    <compression>Compression Type: Hardware [if available, otherwise none]</compression>
    <verify_option>WARNING: The option 'Verify after backup completes' was not selected. Performing a verify operation to make sure that media can be read after the backup has completed is recommended.</verify_option>
    <filler>======================================================================</filler>
    - <machine>
    <machine_name>TGBSAP4.Tetley.Grp</machine_name>
    <info>Network control connection is established between 10.22.2.18:3271 <--> 10.22.2.4:10000</info>
    <info>Network data connection is established between 10.22.2.18:3301 <--> 10.22.2.4:3094</info>
    - <set>
    <set_resource_name>TGBSAP4.Tetley.Grp</set_resource_name>
    <tape_name>Family Name: "Media created 25/09/2011 13:59:55"</tape_name>
    - <volume>
    <display_volume>Backup of "TGBSAP4.Tetley.Grp "</display_volume>
    </volume>
    <description>Backup set #45 on storage media #1 Backup set description: "Weekly Full Backup"</description>
    <backup_type>Backup Method: Full - Back up entire database or filegroup</backup_type>
    <agent_started>Microsoft SQL Server Agent: Started</agent_started>
    <start_time>Backup started on 26/09/2011 at 01:01:45.</start_time>
    - <database>
    <database>Database PRD</database>
    </database>
    - <database>
    <database>Database master</database>
    </database>
    - <database>
    <database>Database model</database>
    </database>
    - <database>
    <database>Database msdb</database>
    </database>
    <end_time>Backup completed on 26/09/2011 at 02:42:25.</end_time>
    - <summary>
    <backed_up_database>Backed up 4 databases</backed_up_database>
    <new_processed_bytes>Processed 573363576542 bytes in 1 hour, 40 minutes, and 40 seconds.</new_processed_bytes>
    <vlm_hist_rateformat2>Throughput rate: 5432 MB/min</vlm_hist_rateformat2>
    </summary>
    <filler>----------------------------------------------------------------------</filler>
    </set>
    </machine>
    </backup>
    - <footer>
    <filler>======================================================================</filler>
    <end_time>Job ended: 26 September 2011 at 02:43:12</end_time>
    <engine_completion_status>Job completion status: Successful</engine_completion_status>
    <filler>======================================================================</filler>
    <completeStatus>19</completeStatus>
    </footer>
    </joblog>

    1. your code does not compile (in your main method you try to create an instance of a class which does not exist).
    2. your XML document is not well formed.
    +[Fatal Error] test.xml:34:74: The content of elements must consist of well-formed character data or markup.+
    org.xml.sax.SAXParseException: The content of elements must consist of well-formed character data or markup.
    Maybe there are other problems but you can start by fixing these.

  • Need help in Parsing XML Document in Oracle

    Hello Experts,
    I urgently need your help. We have xml document on the Web but not on the File System. How can I parse the xml document on the web in Oracle.
    Any link, blog or sample code would be appreciated.
    Your help would be appreciated.
    Kind Regards,
    Bhavin
    London, UK

    This breaks down to two issues
    1) Getting the XML into Oracle
    2) Parsing the XML inside Oracle
    For #1, the first two options that come to my mind are httpuirtype and utl_http. Both can be used to get information from a URL that understands HTTP requests.
    For #2, you can treat the XML as a DOMDocument or XMLType to parse it. You also could parse it via a SQL statement using XQuery or XMLTable as well.
    Many of those examples can be found on the {forum:id=34} forum or [Marco&apos;s blog|http://www.liberidu.com/blog/]. A few parsing examples that I've done can be seen at {message:id=3610259}, make sure to also follow the link I put in there to a previous example before that.

  • Urgent please- need help to retreive all values within a range

    Hi,
    I need to retreive all the values(ID) within a range no matter if it is available in the database or not. I just need this in a sql query not a stored proc.
    for ex:
    select id, name, age
    from employee
    where id between (1 and 10)
    It returns
    id name age
    1 x 22
    3 y 26
    4 z 23
    10 c 32
    I need a query which should return values as follows.
    id name age
    1 x 22
    2
    3 y 26
    4 z 23
    5
    6
    7
    8
    9
    10 c 32
    quick replies will be appreciated.

    This is one way of doing
    select decode(id,null,lev,id),name,age from employee,(select level lev from dual
    connect by level < 11)
    where employee.id(+)=lev
    The above will display between 1 and 10. If you want to specify some other range then the below query will do,
    select decode(id,null,lev,id),name,age from employee,(select level lev from dual
    connect by level <=10
    minus
    select level lev from dual
    connect by level <5)
    where employee.id(+)=lev
    The above query will display between 5 and 10

  • Need help with SQL conditions

    Hi All,
    I have a requirement to split the below query based on conditions. This should be done in SQL.
    SELECT cv.chr_val_code MOD_CODE,
           cv.chr_val_id MOD_ID,
           f_char_value_dscr(cv.chr_val_id, 4,1) MOD_DSCR,
           f_char_value_dscr(schsg.prnt_chr_val_id,4, 1) MOD_SCHEMA,
           cv.mod_typ MOD_TYPE,
           f_char_value_dscr(sgpg.prnt_chr_val_id,4,1) MOD_SUPERGROUP,
           f_char_value_dscr(sgpg.chld_chr_val_id,4,1) MOD_PRODUCTGROUP,
           f_char_value_dscr(lpgpc.CHLD_CHR_VAL_ID,4,1) "LOCAL PC",
           f_char_value_dscr(lpgpc.PRNT_CHR_VAL_ID,4,1) "LOCAL PRODUCTGROUP",
           f_char_value_dscr(lsgpg.CHLD_CHR_VAL_ID,4,1) "LOCAL SUPERGROUP",
           cv.cnsldtd_item_mod MOD_CONSOLIDATED
    FROM   chr_val_t cv
    INNER JOIN chr_t c
    ON  c.chr_id         = cv.chr_id
    AND c.chr_typ_ref_id = pkg_grd_global.f_get_ref_id_by_val('GLOBAL MODULE','CHARACTERISTIC TYPE')
    OR  c.chr_typ_ref_id = pkg_grd_global.f_get_ref_id_by_val('LOCAL PC','CHARACTERISTIC TYPE')
    INNER JOIN hier_elmnt_t pgmod
    ON  cv.chr_val_id    = pgmod.chld_chr_val_id
    INNER JOIN hier_elmnt_t sgpg
    ON  sgpg.chld_chr_val_id  = pgmod.prnt_chr_val_id
    INNER JOIN hier_elmnt_t schsg
    ON  schsg.chld_chr_val_id = sgpg.prnt_chr_val_id
    INNER JOIN hier_elmnt_t lpgpc
    ON    cv.chr_val_id = lpgpc.CHLD_CHR_VAL_ID
    INNER JOIN hier_elmnt_t lsgpg
    ON    lsgpg.CHLD_CHR_VAL_ID = lpgpc.PRNT_CHR_VAL_ID
    WHERE cv.del_ind    = 'N' and c.rgn_id =   9 --GLOBAL REGION ID
    Basically what i need to do now is, say suppose c.rgn_id = 9 then i need to show the below fields
    cv.chr_val_id MOD_ID,
    f_char_value_dscr(cv.chr_val_id, 4,1) MOD_DSCR,
    f_char_value_dscr(schsg.prnt_chr_val_id,4, 1) MOD_SCHEMA,
    cv.mod_typ MOD_TYPE,
    f_char_value_dscr(sgpg.prnt_chr_val_id,4,1) MOD_SUPERGROUP,
    f_char_value_dscr(sgpg.chld_chr_val_id,4,1) MOD_PRODUCTGROUP
    and if c.rgn_id != 9 then i need to show
    f_char_value_dscr(lpgpc.CHLD_CHR_VAL_ID,4,1) "LOCAL PC",
    f_char_value_dscr(lpgpc.PRNT_CHR_VAL_ID,4,1) "LOCAL PRODUCTGROUP",
    f_char_value_dscr(lsgpg.CHLD_CHR_VAL_ID,4,1) "LOCAL SUPERGROUP",
    cv.cnsldtd_item_mod MOD_CONSOLIDATED
    both the above 2 split conditins should be fetching from the same FROM clause
    pls advise..

    Hi Harry (nice name by the way),
    Do you actually want to have different numbers of columns in the output or do you just want null shown if rgn_id is/isnt 9?
    If you just want nulls then you can do it easily with a case statement
    i.e. case rgn_id=9 then xxx else xxx - you can google an example easy enough
    If you want dynamic columns it gets more complicated and you may have to look at pipelined functions or some other solution to do this.
    Cheers,
    Harry

Maybe you are looking for