Parsing a string in PL/SQL?

I am parsing a string in PL/SQL and at a certain point(Length 45) of the string I would like to add a carriage return (Chr(10)), then continue with the string at that point and then again if the string is greater than Length 45 add a carriage return.
I program in Powerbuilder and have figured it out, but I have a problem when trying to add a carriage return at a certain point in the string in PL/SQL. There is the REPLACE(), but that will replace everything, but I only want to add it at that certain point of the string. With the PB function I can add the carriage return at a certain point, see code:
Li_pos = PosA( Ps_data, '*')
DO WHILE Li_pos > 0
ll_length = Li_pos - ll_old_pos
IF ll_length > 45 THEN
ll_old_pos = Li_pos
Ps_data = ReplaceA( Ps_data, Li_Pos, 1, ls_carriage_rtn) **This function gives me the ability to add a carriage return at a certain point in the string. **
Li_pos = PosA( Ps_data, '*', Li_pos + 1 + ls_carriage_rtn)
ELSE
Li_pos = PosA( Ps_data, '*', Li_pos + 1)
END IF
LOOP
I have incorporated the same logic in PL/SQL but I am looking for something similar to the ReplaceA function in PB, that will replace at a certain point in a string. I use an '*' as a placeholder and measure the length. Below is the PL/SQL code:
t_pos NUMBER;
t_old_pos NUMBER;
t_length NUMBER;
BEGIN
t_old_pos := 0;
t_pos := INSTR(in_model_list, '*');
WHILE t_pos > 0 LOOP
t_length := t_pos - t_old_pos; -- This looks at current position minus the old position, measures the length
IF t_length > 45 THEN
t_old_pos := t_pos;
*** add that carriage return
t_pos := INSTR(in_model_list, '*', t_pos + 1 + Chr(10)); -- get the new position
NULL;
ELSE
t_pos := INSTR(in_model_list, '*', t_pos + 1);
END IF;
NULL;
END LOOP;
Here is the data, what it looks like: William 112,* 500-A,* 500-U,* 520,* 560-A,* 560-E,* 680-E,* 680-F,* 680-V*
Any help would be much appreciated.
Thank you,
William
Edited by: William on Feb 28, 2012 6:56 AM

Frank Kulash wrote:
[example]I played with your example and came to this:SQL> WITH my_string AS
  2         (SELECT '1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890'
  3                   AS mt
  4            FROM DUAL)
  5     ,  line_length AS
  6         (SELECT 13 AS chars
  7            FROM DUAL)
  8      SELECT LISTAGG (REGEXP_SUBSTR (mt,'(.{'|| line_length.chars|| '})', 1, LEVEL),chr(10)) WITHIN GROUP (ORDER BY LEVEL)
  9             ||chr(10)
10             ||substr(mt,-mod(LENGTH (mt),line_length.chars)) as wrapped_text
11        FROM my_string
12        CROSS JOIN line_length
13  CONNECT BY LEVEL < 1+LENGTH (mt) ;
WRAPPED_TEXT
1234567890123
4567890123456
7890123456789
0123456789012
3456789012345
6789012345678
9012345678901
2345678901234
5678901234567
8901234567890
1234567890123
WRAPPED_TEXT
4567890123456
7890
SQL>*[Edit]* annotated that this is 11g only...
Edited by: T.PD on 29.02.2012 21:17

Similar Messages

  • Passing / parsing XML String IN / OUT from PL / SQL package

    Hello, People !
    I am wondering where can I find exact info (with code sample) about following :
    We use Oracle 8.1.6 and 8.1.7. I need to pass an XML String (could be from VARCHAR2 to CLOB) from VB 6.0 to PL/SQL package. Then I need to use built in PL/SQL XML parser to parse given string (could be large hierarchy of nodes)
    and the return some kind of cursor thru I can loop and insert data into
    different db Tables. (The return value may have complex parent/child data relationship - so I am not sure If this should be a cursor)
    I looked online many site for related info - can't find what I am looking
    for - seems like should be a common question.
    Thanx a lot !

    Hello, People !
    I am wondering where can I find exact info (with code sample) about following :
    We use Oracle 8.1.6 and 8.1.7. I need to pass an XML String (could be from VARCHAR2 to CLOB) from VB 6.0 to PL/SQL package. Then I need to use built in PL/SQL XML parser to parse given string (could be large hierarchy of nodes)
    and the return some kind of cursor thru I can loop and insert data into
    different db Tables. (The return value may have complex parent/child data relationship - so I am not sure If this should be a cursor)
    I looked online many site for related info - can't find what I am looking
    for - seems like should be a common question.
    Thanx a lot !

  • How to get numeric data from a string using t-sql

    Hi All,
    I have a table with 2 columns ID as Int and Message as nvarchar(max)
    Create table Sample
    ID int not null,
    Message nvarchar(max) null,
    CONSTRAINT [PK_ID_Msg] PRIMARY KEY CLUSTERED
    ID asc
    Insert statement:
    INSERT INTO
    Sample (ID, Message)
    VALUES (1, 'X_YRS: 00 ; X_MONS: 18 ; X_DAYS: 000 ; Y_YRS: 00 ; Y_MONS: 16 ; Y_DAYS: 011 ; Z: 1 ; Z_DATE: 09/04/2014
    INSERT INTO Sample (ID, Message) VALUES (2, 'X_YRS: 01 ; X_MONS: 15 ; X_DAYS: 010 ; Y_YRS: 00 ; Y_MONS: 18 ; Y_DAYS: 017
     ; Z: 1
     ; Z_DATE: 06/02/2012')
    Data in the table looks like:
    ID             Message
    1       X_YRS: 00 ; X_MONS: 18 ; X_DAYS: 000 ; Y_YRS: 00 ; Y_MONS: 16 ; Y_DAYS: 011 ; Z: 1 ; Z_DATE: 09/04/2014
    2       X_YRS: 01 ; X_MONS: 15 ; X_DAYS: 010 ; Y_YRS: 00 ; Y_MONS: 18 ; Y_DAYS: 017 ; Z: 1 ; Z_DATE: 06/02/2012
    Need out put as below, just with numeric data:
    ID      X-Column         Y-Column         
    1       00 18 000        00 16 011
    2       01 15 010        00 18 017
    So, please I need t-SQL to get above output.
    Thanks in advance.
    RH
    sql

    ;With CTE
    AS
    SELECT s.ID,RTRIM(LTRIM(STUFF(Val,1,CHARINDEX(':',Val),''))) AS Val,RTRIM(LTRIM(LEFT(Val,CHARINDEX('_',Val+'_')-1))) AS Pattern,
    --ROW_NUMBER() OVER (PARTITION BY LEFT(Val,CHARINDEX('_',Val+'_')-1) ORDER BY RTRIM(LTRIM(STUFF(Val,1,CHARINDEX(':',Val),'')))*1)
    f.ID AS Seq
    FROM Sample s
    CROSS APPLY dbo.ParseValues(s.[Message],';')f
    WHERE ISNUMERIC(RTRIM(LTRIM(STUFF(Val,1,CHARINDEX(':',Val),'')))+'0.0E0')=1
    SELECT ID,
    STUFF((SELECT ' ' + Val FROM CTE WHERE ID = c.ID AND Pattern = 'X' ORDER BY Seq FOR XML PATH('')),1,1,'') AS XCol,
    STUFF((SELECT ' ' + Val FROM CTE WHERE ID = c.ID AND Pattern = 'Y' ORDER BY Seq FOR XML PATH('')),1,1,'') AS YCol,
    STUFF((SELECT ' ' + Val FROM CTE WHERE ID = c.ID AND Pattern = 'Z' ORDER BY Seq FOR XML PATH('')),1,1,'') AS ZCol
    FROM (SELECT DISTINCT ID FROM CTE)c
    ParseValues can be found here
    http://visakhm.blogspot.in/2010/02/parsing-delimited-string.html
    Numeric check logic is as per below
    http://visakhm.blogspot.in/2014/03/checking-for-integer-or-decimal-values.html
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

  • Parsing a string in a sproc

    I have a Java class that calls a stored proc and passes a stringbuffer object to it. The sproc should parse the string to retrieve the different ids that are concatenated in the stringbuffer and for each id retrieve a row from a table and in the end return a cursor containing the returned rows.Can anyone help me out with the parsing logic for a pipe delimited string.
    Tathagata

    This might help you. If you want to handle the cursor in java, then convert the below into a function which returns the cursor.
    SQL> CREATE TABLE EMP(ENAME VARCHAR2(100),ENO NUMBER(5),DEPT NUMBER(5))
      2  /
    Table created.
    SQL> INSERT INTO EMP VALUES('SCOTT',1,2);
    1 row created.
    SQL> INSERT INTO EMP VALUES('TIGER',2,5);
    1 row created.
    SQL> INSERT INTO EMP VALUES('THOMAS',3,10);
    1 row created.
    SQL> INSERT INTO EMP VALUES('PETER',4,10);
    1 row created.
    SQL> INSERT INTO EMP VALUES('HARRY',7,10);
    1 row created.
    SQL> CREATE OR REPLACE PROCEDURE PARSE_STRING(STR VARCHAR2)
      2  AS
      3  TYPE EmpCurTyp IS REF CURSOR;
      4  emp_cv EmpCurTyp;
      5  STRING VARCHAR2(1000);
      6  type emp_t is table of emp%rowtype;
      7  emp_tab emp_t;
      8  BEGIN
      9  STRING := REPLACE(STR,'|',',');
    10  OPEN emp_cv FOR 'SELECT ENAME,ENO,DEPT FROM EMP WHERE ENO IN('||string||')';
    11  FETCH emp_cv BULK COLLECT INTO EMP_TAB;
    12  CLOSE emp_cv;
    13  FOR I IN 1..EMP_TAB.LAST
    14  LOOP
    15  DBMS_OUTPUT.PUT_LINE(EMP_TAB(I).ENAME);
    16  END LOOP;
    17  EXCEPTION
    18  WHEN OTHERS THEN
    19  DBMS_OUTPUT.PUT_LINE('ERROR OCCURED ' || SQLCODE ||' ' || SQLERRM);
    20  END;
    21  /
    Procedure created.
    SQL> set serveroutput on;
    SQL> BEGIN
      2  PARSE_STRING('1|2|3|4');
      3  END;
      4  /
    SCOTT
    TIGER
    THOMAS
    PETER
    PL/SQL procedure successfully completed.
    SQL>Regards,
    Mohana

  • Parsing a string in a given order

    Hi All,
    I want to parse a string and rank it in a given order.
    Eg : i have a string as 'A | B | C | D'. I would like to parse this string and give a rank in order.
    It should appear as below.
    Parsed string order
    D 1
    C 2
    B 3
    A 4
    Any help is greatly appreciated..

    A database version would help us providing you with a relevant solution.
    Starting with 10g, you can do :
    SQL> var my_str varchar2(30)
    SQL> exec :my_str := 'A|B|C|D'
    PL/SQL procedure successfully completed
    SQL> select item
      2       , row_number() over(order by item desc) as rank
      3  from (
      4    select regexp_substr(:my_str,'[^|]+',1,level) as item
      5    from dual
      6    connect by level <= length(regexp_replace(:my_str,'[^|]+')) + 1
      7  );
    ITEM                    RANK
    D                          1
    C                          2
    B                          3
    A                          4
    In 11.2 :
    SQL> select *
      2  from xmltable(
      3       'for $i in ora:tokenize($str,"\|") order by $i descending return $i'
      4       passing 'A|B|C|D' as "str"
      5       columns item varchar2(10) path '.'
      6             , rank for ordinality
      7       )
      8  ;
    ITEM             RANK
    D                   1
    C                   2
    B                   3
    A                   4
    Edited by: odie_63 on 11 janv. 2012 12:56 - added 11.2

  • Convert a String to java.sql.Date Format

    Hi,
    I am having a String of containing date in the format 'dd/mm/yyyy' OR 'dd-MMM-YYYY' OR 'mm-dd-yyyy' format. I need to convert the string to java.sql.Date object so that I can perform a query the database for the date field. Can any one suggest me with the code please.
    Regards,
    Smitha

    import java.text.SimpleDateFormat;
    import java.text.ParseException;
    import java.util.Date;
    public class TestDateFormat
         public static void main(String args[])
              SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
              System.out.println(sdf.isLenient());
              try
                   Date d1 = sdf.parse("07-11-2001");
                   System.out.println(d1);
                   Date d2 = sdf.parse("07:11:2001");
                   System.out.println(d2);
              catch(ParseException e)
                   System.out.println("Error format, " + e);
    See class DateFormat and SimpleDateFormat for detail.

  • Parse complex XML in PL/SQL

    have complex XML with depth level 10. I need to parse and store data into tables from XML. I am able to parse simple XML but not complex. Could any body suggest me the required steps to parse complex XML in PL/SQL?

    Based on response from mdrake on this thread:
    Re: XML file processing into oracle
    Reading XML using a schema...
    declare
      SCHEMAURL VARCHAR2(256) := 'http://xmlns.example.org/xsd/testcase.xsd';
      XMLSCHEMA VARCHAR2(4000) := '<?xml version="1.0" encoding="UTF-8"?>
         <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xdb="http://xmlns.oracle.com/xdb" xdb:storeVarrayAsTable="true">
            <xs:element name="cust_order" type="cust_orderType" xdb:defaultTable="CUST_ORDER_TBL"/>
            <xs:complexType name="groupType" xdb:maintainDOM="false">
                    <xs:sequence>
                            <xs:element name="item" type="itemType" maxOccurs="unbounded"/>
                    </xs:sequence>
                    <xs:attribute name="id" type="xs:byte" use="required"/>
            </xs:complexType>
            <xs:complexType name="itemType" xdb:maintainDOM="false">
                    <xs:simpleContent>
                            <xs:extension base="xs:string">
                                    <xs:attribute name="id" type="xs:short" use="required"/>
                                    <xs:attribute name="name" type="xs:string" use="required"/>
                            </xs:extension>
                    </xs:simpleContent>
            </xs:complexType>
            <xs:complexType name="cust_orderType" xdb:maintainDOM="false">
                    <xs:sequence>
                            <xs:element name="group" type="groupType" maxOccurs="unbounded"/>
                    </xs:sequence>
                    <xs:attribute name="cust_id" type="xs:short" use="required"/>
            </xs:complexType>
         </xs:schema>';
      INSTANCE  CLOB :=
    '<cust_order cust_id="12345">
      <group id="1">
        <item id="1" name="Standard Mouse">100</item>
        <item id="2" name="Keyboard">100</item>
        <item id="3" name="Memory Module 2Gb">200</item>
        <item id="4" name="Processor 3Ghz">25</item>
        <item id="5" name="Processor 2.4Ghz">75</item>
      </group>
      <group id="2">
        <item id="1" name="Graphics Tablet">15</item>
        <item id="2" name="Keyboard">15</item>
        <item id="3" name="Memory Module 4Gb">15</item>
        <item id="4" name="Processor Quad Core 2.8Ghz">15</item>
      </group>
      <group id="3">
        <item id="1" name="Optical Mouse">5</item>
        <item id="2" name="Ergo Keyboard">5</item>
        <item id="3" name="Memory Module 2Gb">10</item>
        <item id="4" name="Processor Dual Core 2.4Ghz">5</item>
        <item id="5" name="Dual Output Graphics Card">5</item>
        <item id="6" name="28inch LED Monitor">10</item>
        <item id="7" name="Webcam">5</item>
        <item id="8" name="A3 1200dpi Laser Printer">2</item>
      </group>
    </cust_order>';                
    begin
      dbms_xmlschema.registerSchema
         schemaurl       => SCHEMAURL
        ,schemadoc       => XMLSCHEMA
        ,local           => TRUE
        ,genTypes        => TRUE
        ,genBean         => FALSE
        ,genTables       => TRUE
        ,ENABLEHIERARCHY => DBMS_XMLSCHEMA.ENABLE_HIERARCHY_NONE
      execute immediate 'insert into CUST_ORDER_TBL values (XMLTYPE(:INSTANCE))' using INSTANCE;
    end;
    desc CUST_ORDER_TBL
    --SQL> desc CUST_ORDER_TBL
    -- Name                                                                                                                                    Null?    Type
    -- TABLE of SYS.XMLTYPE(XMLSchema "http://xmlns.example.org/xsd/testcase.xsd" Element "cust_order") STORAGE Object-relational TYPE "cust_orderType222_T"
    set autotrace on explain
    set pages 60 lines 164 heading on
    col cust_id format a8
    select extract(object_value,'/cust_order/@cust_id') as cust_id
          ,grp.id as group_id, itm.id as item_id, itm.inm as item_name, itm.qty as item_qty
    from   CUST_ORDER_TBL
          ,XMLTABLE('/cust_order/group'
                    passing object_value
                    columns id   number       path '@id'
                           ,item xmltype      path 'item'
                   ) grp
          ,XMLTABLE('/item'
                    passing grp.item
                    columns id   number       path '@id'
                           ,inm  varchar2(30) path '@name'
                           ,qty  number       path '.'
                   ) itm
    CUST_ID    GROUP_ID    ITEM_ID ITEM_NAME                        ITEM_QTY
    12345             1          1 Standard Mouse                        100
    12345             1          2 Keyboard                              100
    12345             1          3 Memory Module 2Gb                     200
    12345             1          4 Processor 3Ghz                         25
    12345             1          5 Processor 2.4Ghz                       75
    12345             2          1 Graphics Tablet                        15
    12345             2          2 Keyboard                               15
    12345             2          3 Memory Module 4Gb                      15
    12345             2          4 Processor Quad Core 2.8Ghz             15
    12345             3          1 Optical Mouse                           5
    12345             3          2 Ergo Keyboard                           5
    12345             3          3 Memory Module 2Gb                      10
    12345             3          4 Processor Dual Core 2.4Ghz              5
    12345             3          5 Dual Output Graphics Card               5
    12345             3          6 28inch LED Monitor                     10
    12345             3          7 Webcam                                  5
    12345             3          8 A3 1200dpi Laser Printer                2
    17 rows selected.Need at least 10.2.0.3 for performance i.e. to avoid COLLECTION ITERATOR PICKLER FETCH in execution plan...
    On 10.2.0.1:
    Execution Plan
    Plan hash value: 3741473841
    | Id  | Operation                          | Name                   | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT                   |                        | 24504 |    89M|   873   (1)| 00:00:11 |
    |   1 |  NESTED LOOPS                      |                        | 24504 |    89M|   873   (1)| 00:00:11 |
    |   2 |   NESTED LOOPS                     |                        |     3 | 11460 |   805   (1)| 00:00:10 |
    |   3 |    TABLE ACCESS FULL               | CUST_ORDER_TBL         |     1 |  3777 |     3   (0)| 00:00:01 |
    |*  4 |    INDEX RANGE SCAN                | SYS_IOT_TOP_774117     |     3 |   129 |     1   (0)| 00:00:01 |
    |   5 |   COLLECTION ITERATOR PICKLER FETCH| XMLSEQUENCEFROMXMLTYPE |       |       |            |       |
    Predicate Information (identified by operation id):
       4 - access("NESTED_TABLE_ID"="CUST_ORDER_TBL"."SYS_NC0000900010$")
           filter("SYS_NC_TYPEID$" IS NOT NULL)
    Note
       - dynamic sampling used for this statementOn 10.2.0.3:
    Execution Plan
    Plan hash value: 1048233240
    | Id  | Operation               | Name              | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT        |                   |    17 |   132K|   839   (0)| 00:00:11 |
    |   1 |  NESTED LOOPS           |                   |    17 |   132K|   839   (0)| 00:00:11 |
    |   2 |   MERGE JOIN CARTESIAN  |                   |    17 |   131K|   805   (0)| 00:00:10 |
    |   3 |    TABLE ACCESS FULL    | CUST_ORDER_TBL    |     1 |  3781 |     3   (0)| 00:00:01 |
    |   4 |    BUFFER SORT          |                   |    17 | 70839 |   802   (0)| 00:00:10 |
    |*  5 |     INDEX FAST FULL SCAN| SYS_IOT_TOP_56154 |    17 | 70839 |   802   (0)| 00:00:10 |
    |*  6 |   INDEX UNIQUE SCAN     | SYS_IOT_TOP_56152 |     1 |    43 |     2   (0)| 00:00:01 |
    |*  7 |    INDEX RANGE SCAN     | SYS_C006701       |     1 |       |     0   (0)| 00:00:01 |
    Predicate Information (identified by operation id):
       5 - filter("SYS_NC_TYPEID$" IS NOT NULL)
       6 - access("SYS_NTpzENS1H/RwSSC7TVzvlqmQ=="."NESTED_TABLE_ID"="SYS_NTnN5b8Q+8Txi9V
                  w5Ysl6x9w=="."SYS_NC0000600007$")
           filter("SYS_NC_TYPEID$" IS NOT NULL AND
                  "NESTED_TABLE_ID"="CUST_ORDER_TBL"."SYS_NC0000900010$")
       7 - access("SYS_NTpzENS1H/RwSSC7TVzvlqmQ=="."NESTED_TABLE_ID"="SYS_NTnN5b8Q+8Txi9V
                  w5Ysl6x9w=="."SYS_NC0000600007$")
    Note
       - dynamic sampling used for this statement-----
    -- CLEAN UP
    DROP TABLE CUST_ORDER_TBL purge;
    exec dbms_xmlschema.deleteschema('http://xmlns.example.org/xsd/testcase.xsd');

  • Parsing a string using StringTokenizer

    Hi,
    I want to parse a string such as
    String input = ab{cd}:"abc""de"{
    and the extracted tokens should be as follows
    ab
    cd
    "abc""de"
    As a result, I used the StringTokenizer class with deilmeter {,},:
    StringTokenizer tokenizer = new StringTokenizer(input,"{}:", true);
    In this was, I can separate the tokens and also can get the delimeters. The problem is I don't know how to parse the string that has double quote on it. If a single quote " is taken as a delimeter then
    ", abc, ",", de," all of them will be taken as a separate token. My intention is to get the whole string inside the double quote as a token including the quotes on it. Moreover, if there is any escape character "", it should be also included in the token. Help please.
    Thanks

    A bit of a "sticky tape"-solution...
    import java.util.StringTokenizer;
    public class Test {
        public static void main(String[] args) {
            String input = "ab{cd}:\"abc\"\"de\"";
            StringTokenizer st = new StringTokenizer(input, "{}:", true);
            while(st.hasMoreTokens()) {
            String token = st.nextToken();
            if(token.startsWith("\"") && token.endsWith("\"")) {
            token = token.substring(1,token.length()-1);
                System.out.println(token);
    }

  • How to Parse a string into an XML DOM ?

    Hi,
    I want to parse a String into an XML DOM. Not able to locate any parser which supports that. Any pointers to this?

    Download Xerces from xml.apache.org. Place the relevant JAR's on your classpath. Here is sample code to get a DOM document reference.
    - Saish
    public final class DomParser extends Object {
         // Class Variables //
         private static final DocumentBuilder builder;
         private static final String JAXP_SCHEMA_LANGUAGE =
             "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
         /** W3C schema definitions */
         private static final String W3C_XML_SCHEMA =
             "http://www.w3.org/2001/XMLSchema";
         // Constructors //
         static {
              try {
                   DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                   factory.setNamespaceAware(true);
                   factory.setValidating(true);
                   factory.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
                   builder = factory.newDocumentBuilder();
                   builder.setErrorHandler(new ErrorHandler() {
                       public void warning(SAXParseException e) throws SAXException {
                           System.err.println("[warning] "+e.getMessage());
                       public void error(SAXParseException e) throws SAXException {
                           System.err.println("[error] "+e.getMessage());
                       public void fatalError(SAXParseException e) throws SAXException {
                           System.err.println("[fatal error] "+e.getMessage());
                           throw new XmlParsingError("Fatal validation error", e);
              catch (ParserConfigurationException fatal) {
                   throw new ConfigurationError("Unable to create XML DOM document parser", fatal);
              catch (FactoryConfigurationError fatal) {
                   throw new ConfigurationError("Unable to create XML DOM document factory", fatal);
         private DomParser() {
              super();
         // Public Methods //
         public static final Document newDocument() {
              return builder.newDocument();
         public static final Document parseDocument(final InputStream in) {
              try {
                   return builder.parse(in);
              catch (SAXException e) {
                   throw new XmlParsingError("SAX exception during parsing.  Document is not well-formed or contains " +
                        "illegal characters", e);
              catch (IOException e) {
                   throw new XmlParsingError("Encountered I/O exception during parsing", e);
    }- Saish

  • Parsing formatted String to Int

    How can I parse formatted string to Integer ?
    I have a formated string like this $900,000 and I need to convert it to 900000 so I could do calculations with it.
    I tried something like this
    NumberFormat nf = NumberFormat.getIntegerInstance(request.getLocale());
    ttlMargin=nf.parse(screenVal);I got this exception
    "java.lang.NumberFormatException: For input string: "$1,050,000""

    I am working on the JSP file that provides
    margins,sales etc. I am reading this data off the
    screen where it is beeing displayed according to the
    accounting practices.
    That's why I get it as a formatted string and why I
    am trying covert that string to the numberScreen-scraping is a problematic, bad design. It sounds like what you really want is to call a web service which returns its results as data that a program can understand (XML, for example), not HTML (which is meant more for humans to read). I know, you probably can't change the design at this point... just food for thought. In the meantime, you'll probably have to manually parse those strings yourself by stripping out the '$' and ',' characters and then use parseInt on the result.

  • How to parse a string containing xml data

    Hi,
    Is it possible to parse a string containing xml data into a array list?
    my string contains xml data as <blood_group>
         <choice id ='1' value='A +ve'/>
         <choice id ='2' value='B +ve'/>
             <choice id ='3' value='O +ve'/>
    </blood_group>how can i get "value" into array list?

    There are lot of Java XML parsing API's available, e.g. JAXP, DOM4J, JXPath, etc.
    Of course you can also write it yourself. Look which methods the String API offers you, e.g. substring and *indexOf.                                                                                                                                                                                                                                                                                                                                                                                                               

  • How to parse a string in CVP 7.0(1). Is there a built-in java class, other?

    Hi,
    I need to parse,in CVP 7.0(1), the BAAccountNumber variable passed by the ICM dialer.  Is there a built-in java class or other function that would help me do this?
    Our BAAccountNumber variable looks something like this: 321|XXX12345678|1901|M. In IP IVR I use the "Get ICM Data" object to read the BAAccountNumber variable from ICM and then I use the "token index" feature to parse the variable (picture below).
    Alternately, IP IVR also has a Java class that allows me to do this; the class is "java.lang.String" and the method is "public int indexOf(String,int)"
    Is there something equivalent in CVP 7.0(1)?
    thanks

    Thanks again for your help.  This is what I ended up doing:
    This configurable action element takes a string seperated by two "|" (123|123456789|12)
    and returns 3 string variables.
    you can add more output variables by adding to the Setting array below.
    // These classes are used by custom configurable elements.
    import com.audium.server.session.ActionElementData;
    import com.audium.server.voiceElement.ActionElementBase;
    import com.audium.server.voiceElement.ElementData;
    import com.audium.server.voiceElement.ElementException;
    import com.audium.server.voiceElement.ElementInterface;
    import com.audium.server.voiceElement.Setting;
    import com.audium.server.xml.ActionElementConfig;
    public class SOMENAMEHERE extends ActionElementBase implements ElementInterface
         * This method is run when the action is visited. From the ActionElementData
         * object, the configuration can be obtained.
        public void doAction(String name, ActionElementData actionData) throws ElementException
            try {
                // Get the configuration
                ActionElementConfig config = actionData.getActionElementConfig();
                //now retrieve each setting value using its 'real' name as defined in the getSettings method above
                //each setting is returned as a String type, but can be converted.
                String input = config.getSettingValue("input",actionData);
                String resultType = config.getSettingValue("resultType",actionData);
                String resultEntityID = config.getSettingValue("resultEntityID",actionData);
                String resultMemberID = config.getSettingValue("resultMemberID",actionData);
                String resultTFNType = config.getSettingValue("resultTFNType",actionData);
                //get the substring
                //String sub = input.substring(startPos,startPos+numChars);
                String[] BAAcctresults = input.split("\\|");
                //Now store the substring into either Element or Session data as requested
                //and store it into the variable name requested by the Studio developer
                if(resultType.equals("Element")){
                    actionData.setElementData(resultEntityID,BAAcctresults[0]);
                    actionData.setElementData(resultMemberID,BAAcctresults[1]);
                    actionData.setElementData(resultTFNType,BAAcctresults[2]);
                } else {
                    actionData.setSessionData(resultEntityID,BAAcctresults[0]);
                    actionData.setSessionData(resultMemberID,BAAcctresults[1]);
                    actionData.setSessionData(resultTFNType,BAAcctresults[2]);
                actionData.setElementData("status","success");
            } catch (Exception e) {
                //If anything goes wrong, create Element data 'status' with the value 'failure'
                //and return an empty string into the variable requested by the caller
                e.printStackTrace();
                actionData.setElementData("status","failure");
        public String getElementName()
            return "MEDDOC PARSER";
        public String getDisplayFolderName()
            return "SSC Custom";
        public String getDescription()
            return "This class breaks down the BAAccountNumber";
        public Setting[] getSettings() throws ElementException
             //You must define the number of settings here
             Setting[] settingArray = new Setting[5];
              //each setting must specify: real name, display name, description,
              //is it required?, can it only appear once?, does it allow substitution?,
              //and the type of entry allowed
            settingArray[0] = new Setting("input", "Original String",
                       "This is the string from which to grab a substring.",
                       true,   // It is required
                       true,   // It appears only once
                       true,   // It allows substitution
                       Setting.STRING);
            settingArray[1] = new Setting("resultType", "Result Type",
                    "Choose where to store result \n" +
                    "into Element or Session data",
                    true,   // It is required
                    true,   // It appears only once
                    false,  // It does NOT allow substitution
                    new String[]{"Element","Session"});//pull-down menu
            settingArray[1].setDefaultValue("Session");
            settingArray[2] = new Setting("resultEntityID", "EntityID",
              "Name of variable to hold the result.",
              true,   // It is required
              true,   // It appears only once
              true,   // It allows substitution
              Setting.STRING);  
            settingArray[2].setDefaultValue("EntityID");
            settingArray[3] = new Setting("resultMemberID", "MemberID",
                    "Name of variable to hold the result.",
                    true,   // It is required
                    true,   // It appears only once
                    true,   // It allows substitution
                    Setting.STRING);  
            settingArray[3].setDefaultValue("MemberID");
            settingArray[4] = new Setting("resultTFNType", "TFNType",
                      "Name of variable to hold the result.",
                      true,   // It is required
                      true,   // It appears only once
                      true,   // It allows substitution
                      Setting.STRING);  
            settingArray[4].setDefaultValue("TFNType");    
    return settingArray;
        public ElementData[] getElementData() throws ElementException
            return null;

  • Date contructor deprecation : Parsing a String to Date

    Hi All,
    In Java 1.5 the Date() constructor Date(String s) is deprecated. As per the API Documentation DateFormat.Parse() method is used.
    The following code from Java 1.4 version has to be upgraded to Java 1.5.
    Existing Code:
    Date dDate = new Date(sDate);
    Modified Code:
    DateFormat df = DateFormat.getDateInstance();
    Date dDate = df.parse(sDate);
    Here the DateFormat accepts a default formatting style as "Feb 01, 2007" and parses the String.
    If the String sDate belongs to any other formatting style such as "01 Feb, 2007" or "01 Feb, 07" the code piece throws unparsable date error.
    Please give your thougts on this issue to parse the string of any format..
    Thanks,
    Rajesh.

    Hi All,
    In Java 1.5 the Date() constructor Date(String s) is
    deprecated. As per the API Documentation
    DateFormat.Parse() method is used.
    The following code from Java 1.4 version has to be
    upgraded to Java 1.5.
    Existing Code:
    Date dDate = new Date(sDate);
    Modified Code:
    DateFormat df = DateFormat.getDateInstance();
    Date dDate = df.parse(sDate);
    Here the DateFormat accepts a default formatting
    style as "Feb 01, 2007" and parses the String.
    If the String sDate belongs to any other formatting
    style such as "01 Feb, 2007" or "01 Feb, 07" the code
    piece throws unparsable date error.
    Please give your thougts on this issue to parse the
    string of any format..You can't. What date is this: "08/04/24"? 8 April, 1924? 4 August, 2024?
    >
    Thanks,
    Rajesh.

  • External Parser - XML to Pipe Delimited - Sql Loader BETTER DBMS_XMLSTORE

    Hi All,
    If I have got data in GIGs in a complex format.
    Can Using an External Java based XML Parser to convert XML to Pipe Delimited FIle and then Using SQL Loader
    BE BETTER THAN
    Using XSL to convert to Oracle <ROWSET> <ROW> Format and using DBMS_XMLSTORE to load data into tables.
    In terms of:
    Performace
    Scalability
    Exception Handling
    Regards....

    Go to the {forum:id=34} forum and look at the second page of the XML DB FAQ Thread (stickied to the top of the posts). While it doesn't compare using external tools to parse XML and load via SQL*Loader, it does talk about better ways to load large amounts of XML into the DB. This is also a good thread on the subject too from that forum, {thread:id=1096784}

  • Problems parsing a string

    Hi,
    I'm having a problem with parsing a string. Basically, I want to take a string for example: "TomWentToTheShop" and divide it into a coherent sentence (Tom went to the shop).
    I've started the code by breaking the string into a char array, and if the character is a capital then store the index in the array and then do a substring.
    But I don't think this is the best way to solve the problem, if anyone has any ideas it would be greatly appreciated.
    thanks.
    char[] charRequestTypeArray = string.toCharArray();
    for (int i = 1; i < (charRequestTypeArray.length -1); i++) {
    char c = charRequestTypeArray;
    if (Character.isUpperCase(c)) {
    Arrays.fill(storeCapitalIndex, i);
    else{
    Arrays.fill(storeNonCapitalIndex, i);

            String s = "TomWentToTheShop";
            System.out.println(s.charAt(0) + s.substring(1).replaceAll("((?<!^)[A-Z])", " $1").toLowerCase());or even just        System.out.println(s.charAt(0) + s.substring(1).replaceAll("([A-Z])", " $1").toLowerCase());Edited by: sabre150 on Nov 11, 2007 9:40 PM

Maybe you are looking for