How to insert rows from an xml file to a table
im Using Oracle 11g It is showing below error when i execute..
declare
charString varchar2(80);
finalStr varchar2(400) := null;
rowsp integer;
v_FileHandle UTL_FILE.FILE_TYPE;
begin
-- the name of the table as specified in our DTD
xmlgen.setRowsetTag('Zipcodes');
-- the name of the data set as specified in our DTD
xmlgen.setRowTag('mappings');
-- for getting the output on the screen
dbms_output.enable(100000);
-- open the XML document in read only mode
v_FileHandle := utl_file.fopen(TMP_DIR1,'XML_NEW_CITIES.XML', 'r');
loop
BEGIN
utl_file.get_line(v_FileHandle, charString);
exception
when no_data_found then
utl_file.fclose(v_FileHandle);
exit;
END;
dbms_output.put_line(charString);
if finalStr is not null then
finalStr := finalStr || charString;
else
finalStr := charString;
end if;
end loop;
-- for inserting the XML data into the table
rowsp := xmlgen.insertXML('SYS.ZIPCODES',finalStr);
dbms_output.put_line('INSERT DONE '||TO_CHAR(rowsp));
xmlgen.resetOptions;
end;
XML_NEW_CITIES.XML is
<?xml version = '1.0'?>
<Zipcodes>
<mappings Record="4">
<STATE_ABBREVIATION>CA</STATE_ABBREVIATION>
<ZIPCODE>94301</ZIPCODE>
<CITY>Palo Alto</CITY>
</mappings>
<mappings Record="5">
<STATE_ABBREVIATION>CO</STATE_ABBREVIATION>
<ZIPCODE>80323</ZIPCODE>
<ZIP_CODE_EXTN>9277</ZIP_CODE_EXTN>
<CITY>Boulder</CITY>
</mappings>
</Zipcodes>
Error report:
ORA-06550: line 8, column 3:
PLS-00201: identifier 'XMLGEN.SETROWSETTAG' must be declared
ORA-06550: line 8, column 3:
PL/SQL: Statement ignored
ORA-06550: line 10, column 3:
PLS-00201: identifier 'XMLGEN.SETROWTAG' must be declared
ORA-06550: line 10, column 3:
PL/SQL: Statement ignored
ORA-06550: line 14, column 34:
PLS-00201: identifier 'TMP_DIR1' must be declared
ORA-06550: line 14, column 3:
PL/SQL: Statement ignored
ORA-06550: line 31, column 12:
PLS-00201: identifier 'XMLGEN.INSERTXML' must be declared
ORA-06550: line 31, column 3:
PL/SQL: Statement ignored
ORA-06550: line 33, column 3:
PLS-00201: identifier 'XMLGEN.RESETOPTIONS' must be declared
ORA-06550: line 33, column 3:
PL/SQL: Statement ignored
06550. 00000 - "line %s, column %s:\n%s"
*Cause: Usually a PL/SQL compilation error
Edited by: 898235 on Nov 20, 2011 11:02 PM
OK, then did you try the XMLTable example, or are you waiting for someone to write it all down for you? :)
You first have to create an Oracle directory object pointing to the physical location of your file (must be somewhere on the db server or at least a location the db server can access on the network).
Then create the procedure, in this case a simple INSERT SELECT :
SQL> create directory tmp_dir as 'c:\temp';
Directory created
SQL> create table zipcodes (
2 state_abbreviation varchar2(2),
3 zipcode varchar2(5),
4 zip_code_extn varchar2(10),
5 city varchar2(80)
6 );
Table created
SQL> CREATE OR REPLACE PROCEDURE insertZipcodes (
2 p_directory IN VARCHAR2
3 , p_filename IN VARCHAR2
4 )
5 IS
6 BEGIN
7
8 INSERT INTO zipcodes (state_abbreviation, zipcode, zip_code_extn, city)
9 SELECT state_abbreviation
10 , zipcode
11 , zip_code_extn
12 , city
13 FROM XMLTable('/Zipcodes/mappings'
14 passing xmltype(bfilename(p_directory, p_filename), nls_charset_id('AL32UTF8'))
15 columns state_abbreviation varchar2(2) path 'STATE_ABBREVIATION'
16 , zipcode varchar2(5) path 'ZIPCODE'
17 , zip_code_extn varchar2(10) path 'ZIP_CODE_EXTN'
18 , city varchar2(80) path 'CITY'
19 )
20 ;
21
22 END;
23 /
Procedure created
SQL> exec insertZipcodes('TMP_DIR', 'xml_new_cities.xml');
PL/SQL procedure successfully completed
SQL> commit;
Commit complete
SQL> select * from zipcodes;
STATE_ABBREVIATION ZIPCODE ZIP_CODE_EXTN CITY
CA 94301 Palo Alto
CO 80323 9277 Boulder
Similar Messages
-
How to Insert data from an XML file into an Oracle 10g table
Hello,
Please can you help me as I have hit a brick wall with this problem.
We are running version 10g Oracle and we will start receiving XML files with employee data that needs loading into a table, this is the XML file:
<?xml version="1.0"?>
<RECRUITS>
<RECRUIT>
<FIRST_NAME>Gordon</FIRST_NAME>
<LAST_NAME>Brown</LAST_NAME>
<SHORT_NAME>GORDONBROWN</SHORT_NAME>
<APP_NO>00002</APP_NO>
<STATUS>M</STATUS>
<DATE_FROM>21-JUL-2006</DATE_FROM>
<RESOURCE_TYPE>P</RESOURCE_TYPE>
<TITLE>Mr</TITLE>
<DATE_OF_BIRTH>28-DEC-1983</DATE_OF_BIRTH>
<SOCIAL_SEC>AB128456A</SOCIAL_SEC>
<PARTTIME_PCT>1</PARTTIME_PCT>
<SEX>M</SEX>
<ADDRESS_TYPE>1</ADDRESS_TYPE>
<ADDRESS>A HOUSE SOMEWHERE HERE</ADDRESS>
<ZIP_CODE>PE3 LLL</ZIP_CODE>
<PLACE>BOROUGH</PLACE>
<COUNTRY_CODE>UK</COUNTRY_CODE>
<PROVINCE>UK</PROVINCE>
<EMAIL>[email protected]</EMAIL>
</RECRUIT>
(FYI - there may be more than 1 employee in each file so all of the above will be repeated X amount of times)
</RECRUITS>
To make things simple we have created a table which mirrors the XML file completely to load the data into, the SQL i have used is thus:
CREATE TABLE RECRUITMENT
FIRST_NAME VARCHAR2(30),
LAST_NAME VARCHAR2(30),
SHORT_NAME VARCHAR2(30),
APP_NO NUMBER,
STATUS VARCHAR2(1),
DATE_FROM DATE,
RESOURCE_TYPE VARCHAR2(1),
TITLE VARCHAR2(4),
DATE_OF_BIRTH DATE,
SOCIAL_SEC VARCHAR2(9),
PARTTIME_PCT NUMBER,
SEX VARCHAR2(1),
ADDRESS_TYPE VARCHAR2(1),
ADDRESS VARCHAR2(30),
ZIP_CODE VARCHAR2(8),
PLACE VARCHAR2(10),
PROVINCE VARCHAR2(3),
EMAIL VARCHAR2(20)
Every method we try from the numerous documents and so called "user guides" have failed, please can somebody show me the PL/SQL i need to get this files data into the above table?
We need to be able to do this purely through SQL*PLUS as we hope - if we ever get it working manually to create a procuedure that will encapsulate everything so it can be run over and over again.
The XML file is sitting in the XMLDIR and is called REC.XML.
Please help : (Hi, I have got some material for inserting data into oracle table from xml file, this might help you.
Create XML Document Table
create table XML_DOCUMENT_TABLE
FILENAME varchar2(64),
XML_DOCUMENT XMLTYPE
(This will be as per your record details).
Inserting record to Oracle Table
declare
XML_TEXT CLOB := '<smsnotification>
<messageid> 256427844 </messageid>
<protocolid> CO0NPS2KHQ </protocolid>
<notifiedon> 1156123007416 </notifiedon>
<status> 3PBI: Invalid </status>
<additionalinfo> Customer account not active </additionalinfo>
<carrierid> 1175 </carrierid>
</smsnotification>';
begin
insert into XML_DOCUMENT_TABLE values ('Receipt.xml',XMLTYPE(XML_TEXT));
end;
Select Statement
select extractValue(XML_DOCUMENT,'/smsnotification/messageid') Messageid,
extractValue(XML_DOCUMENT,'/smsnotification/status') Status,
extractValue(XML_DOCUMENT,'/smsnotification/carrierid') CarrierID
from XML_DOCUMENT_TABLE; -
While inserting values from a xml file into the database.
Dear Forum Members,
While using Samp10.java (given in XSU!2_ver1_2_1/oracleXSU12/Sample)for inserting values from xml file Sampdoc.xml into database table xmltest_tab1,the error shown below appears on the DOS prompt.
The code for sam10 is:
import oracle.xml.sql.dml.*;
import java.sql.*;
import oracle.jdbc.driver.*;
import oracle.jdbc.*;
import java.net.*;
public class samp10
public static void main(String args[]) throws SQLException
String tabName = "xmltest_tab1";
String fileName = "sampdoc.xml";
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn=DriverManager.getConnection("jdbc:odbc:BookingSealinerScott","scott","tiger");
OracleXMLSave sav = new OracleXMLSave(conn, tabName);
URL url = sav.createURL(fileName);
int rowCount = sav.insertXML(url);
System.out.println(" successfully inserted "+rowCount+
" rows into "+ tabName);
conn.close();
}catch (Exception e){e.printStackTrace();}
The Structure of Sampdoc.xml is:
<?xml version="1.0"?>
<ROWSET>
<ROW num="1">
<EMPNO>7369</EMPNO>
<ENAME>SMITH</ENAME>
<JOB>CLERK</JOB>
</ROW>
<ROW num="2">
<EMPNO>7499</EMPNO>
<ENAME>ALLEN</ENAME>
<JOB>SALESMAN</JOB>
</ROW>
<ROW num="3">
<EMPNO>7521</EMPNO>
<ENAME>WARD</ENAME>
<JOB>SALESMAN</JOB>
</ROW>
</ROWSET>
Description of table xmltest_tab1 is:
SQL> desc xmltest_tab1;
Name Null? Type
EMPNO NUMBER(4)
ENAME CHAR(10)
JOB VARCHAR2(9)
Error Displayed is:
A nonfatal internal JIT (3.00.078(x)) error 'Structured Exception(c0000005)' has
occurred in :
'oracle/xml/sql/dml/OracleXMLSave.cleanLobList ()V': Interpreting method.
Please report this error in detail to http://java.sun.com/cgi-bin/bugreport.cgi
oracle.xml.sql.OracleXMLSQLException: sun.jdbc.odbc.JdbcOdbcConnection
at oracle.xml.sql.dml.OracleXMLSave.saveXML(OracleXMLSave.java:1967)
at oracle.xml.sql.dml.OracleXMLSave.saveXML(OracleXMLSave.java:1880)
at oracle.xml.sql.dml.OracleXMLSave.insertXML(OracleXMLSave.java:1013)
at samp10.main(samp10.java:36)
Press any key to continue . . .
Please send me the solution as soon as possible.
Thanks,
Waiting for your Reply,
Bye,
Vineet Choudhary
Email id: [email protected]
nullGo and read about JDBC. You need to know some basics before asking such a st&*id questions.
Paul -
i'm using indesign for make books. always i need insert quotes from some holy books. so i need to insert text using verse number
i'm not asking about
b
u
l
l
e
t and
n
u
m
b
e
r
i
n
g
sorry for my bad english
my target is simply insert pre typed sorted texts using the verse number. for example. i have Holy Quran full text . it have about 6000 verse. suppose i need chapter 3, verse 5 in to my paragraph. manually i goto that text file and copy the text paste it here. but i need it automatically using page number/ verse number/ unique id. script / addins .
approximately like "data merge " in design. -
How to load movies from a xml file?
I have a movie called "index.swf" and a class called "index.as"
The problem is that loads the movies in the same position.
index.as:
package
import flash.utils.getDefinitionByName;
import flash.display.Loader;
import flash.display.Sprite;
import flash.events.Event;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.display.Loader;
import flash.events.ProgressEvent;
import flash.display.MovieClip;
public class index extends Sprite
private var _xml:XML;
private var swf_id:String
private var swf_m:String
private var swf_x:Number
private var swf_y:Number
private var swf_width:Number
private var swf_height:Number
function startLoad()
var mLoader:Loader = new Loader();
var mRequest:URLRequest = new URLRequest(swf_m);
mLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onCompleteHandler);
mLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onProgressHandler);
mLoader.name=swf_id
mLoader.load(mRequest);
function onCompleteHandler(loadEvent:Event)
loadEvent.currentTarget.content.width=swf_width
loadEvent.currentTarget.content.height=swf_height
addChild(loadEvent.currentTarget.content);
function onProgressHandler(mProgress:ProgressEvent)
var percent:Number = mProgress.bytesLoaded/mProgress.bytesTotal;
trace(percent);
public function index()
loadXMLFile();
private function loadXMLFile():void
var loader= new URLLoader(new URLRequest("/configuracion.xml"));
loader.addEventListener(Event.COMPLETE, loadedCompleteHandler);
private function loadedCompleteHandler(e:Event):void
e.target.removeEventListener(Event.COMPLETE, loadedCompleteHandler);
_xml = XML(e.target.data);
for each (var conf:XML in _xml.secciones.seccion) {
swf_id = conf.id
swf_m = conf.nombre;
swf_x = conf.pos_x
swf_y = conf.pos_y
swf_width = conf.width
swf_height = conf.height
startLoad();
Xml File: "configuracion.xml"
<?xml version="1.0" encoding="utf-8"?>
<config>
<secciones>
<seccion>
<id>1</id>
<nombre>pelicula1.swf</nombre>
<pos_x>20</pos_x>
<pos_y>10</pos_y>
<width>200</width>
<height>200</height>
</seccion>
<seccion>
<id>2</id>
<nombre>pelicula2.swf</nombre>
<pos_x>80</pos_x>
<pos_y>10</pos_y>
<width>200</width>
<height>200</height>
</seccion>
</secciones>
</config>
thanks for your help...thanks rziller
I already tried this,
x,y values work...
height and width values do not work.....
thanks but I fix the problem....
here this...
package
import flash.display.Sprite;
import flash.events.Event;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.display.Loader;
public class index extends Sprite
private var _xml:XML;
private var i:Number=0;
private var Swf_List:Array = new Array();
private var mLoader:Loader;
function startLoad()
mLoader = new Loader();
var mRequest:URLRequest = new URLRequest(Swf_List[i][1]);
mLoader.contentLoaderInfo.addEventListener(Event.INIT, initHandler);
mLoader.load(mRequest);
mLoader.name=Swf_List[i][0]
addChild(mLoader);
function initHandler(event:Event):void {
var ii:Number = event.target.loader.name-1
event.target.loader.x=Swf_List[ii][2]
event.target.loader.y=Swf_List[ii][3]
event.target.loader.width=Swf_List[ii][4];
event.target.loader.height=Swf_List[ii][5];
trace(event.target.loader.name)
public function index()
loadXMLFile();
private function loadXMLFile():void
var loader= new URLLoader(new URLRequest("config.xml"));
loader.addEventListener(Event.COMPLETE, loadedCompleteHandler);
private function loadedCompleteHandler(e:Event):void
e.target.removeEventListener(Event.COMPLETE, loadedCompleteHandler);
_xml = XML(e.target.data);
_xml.ignoreWhitespace=true;
for each (var conf:XML in _xml.secciones.seccion)
Swf_List[i] = [conf.id,conf.nombre,conf.pos_x,conf.pos_y,conf.width,conf.height];
startLoad()
i++;
maybe not the best way....
but it works!!!......... -
How to import data from a text file into a table
Hello,
I need help with importing data from a .csv file with comma delimiter into a table.
I've been struggling to figure out how to use the "Import from Files" wizard in Oracle 10g web-base Enterprise Manager.
I have not been able to find a simple instruction on how to use the Wizard.
I have looked at the Oracle Database Utilities - Overview of Oracle Data Pump and the Help on the "Import: Files" page.
Neither one gave me enough instruction to be able to do the import successfully.
Using the "Import from file" wizard, I created a Directory Object using the Create Directory Object button. I Copied the file from which i needed to import the data into the Operating System Directory i had defined in the Create Directory Object page. I chose "Entire files" for the Import type.
Step 1 of 4 is the "Import:Re-Mapping" page, I have no idea what i need to do on this page. All i know i am not tying to import data that was in one schema into a different schema and I am not importing data that was in one tablespace into a different tablespace and i am not R-Mapping datafiles either. I am importing data from a csv file.
For step 2 of 4, "Import:Options" page, I selected the same directory object i had created.
For step 3 of 4, I entered a job name and a description and selected Start Immediately option.
What i noticed going through the wizard, the wizard never asked into which table do i want to import the data.
I submitted the job and I got ORA-31619 invalid dump file error.
I was sure that the wizard was going to fail when it never asked me into which table do i want to import the data.
I tried to use the "imp" utility in command-line window.
After I entered (imp), i was prompted for the username and the password and then the buffer size as soon as i entered the min buffer size I got the following error and the import was terminated:
C:\>imp
Import: Release 10.1.0.2.0 - Production on Fri Jul 9 12:56:11 2004
Copyright (c) 1982, 2004, Oracle. All rights reserved.
Username: user1
Password:
Connected to: Oracle Database 10g Enterprise Edition Release 10.1.0.2.0 - Produc
tion
With the Partitioning, OLAP and Data Mining options
Import file: EXPDAT.DMP > c:\securParms\securParms.csv
Enter insert buffer size (minimum is 8192) 30720> 8192
IMP-00037: Character set marker unknown
IMP-00000: Import terminated unsuccessfully
Please show me the easiest way to import a text file into a table. How complex could it be to do a simple import into a table using a text file?
We are testing our application against both an Oracle database and a MSSQLServer 2000 database.
I was able to import the data into a table in MSSQLServer database and I can say that anybody with no experience could easily do an export/import in MSSQLServer 2000.
I appreciate if someone could show me how to the import from a file into a table!
Thanks,
Mitra>
I can say that anybody with
no experience could easily do an export/import in
MSSQLServer 2000.
Anybody with no experience should not mess up my Oracle Databases ! -
Problem converting data in XML file to internal table data
Hi all,
I have a requirement. I need to convert an XML file to internal table data and based on that data do Goods Receipt in SAP.
With the help of this blog /people/r.eijpe/blog/2005/11/10/xml-dom-processing-in-abap-part-i--convert-an-abap-table-into-xml-file-using-sap-dom-approach
I am able to convert the XML file to data in SAP. But this blog will display the output on screen as ELELEMNT = nodename VALUE= value of that node.
But I donu2019t want in that way, I want to store all the data in XML file in an internal table so that I can make use of those values and do Goods Recipt in SAP.
Can some one suggest how should I read the data in an internal table.
Here is my code..what changes should I make?
*& Report z_xit_xml_check
REPORT z_xit_xml_check.
TYPE-POOLS: ixml.
TYPES: BEGIN OF t_xml_line,
data(256) TYPE x,
END OF t_xml_line.
DATA: l_ixml TYPE REF TO if_ixml,
l_streamfactory TYPE REF TO if_ixml_stream_factory,
l_parser TYPE REF TO if_ixml_parser,
l_istream TYPE REF TO if_ixml_istream,
l_document TYPE REF TO if_ixml_document,
l_node TYPE REF TO if_ixml_node,
l_xmldata TYPE string.
DATA: l_elem TYPE REF TO if_ixml_element,
l_root_node TYPE REF TO if_ixml_node,
l_next_node TYPE REF TO if_ixml_node,
l_name TYPE string,
l_iterator TYPE REF TO if_ixml_node_iterator.
DATA: l_xml_table TYPE TABLE OF t_xml_line,
l_xml_line TYPE t_xml_line,
l_xml_table_size TYPE i.
DATA: l_filename TYPE string.
PARAMETERS: pa_file TYPE char1024 DEFAULT 'c:\temp\orders_dtd.xml'.
Validation of XML file: Only DTD included in xml document is supported
PARAMETERS: pa_val TYPE char1 AS CHECKBOX.
START-OF-SELECTION.
Creating the main iXML factory
l_ixml = cl_ixml=>create( ).
Creating a stream factory
l_streamfactory = l_ixml->create_stream_factory( ).
PERFORM get_xml_table CHANGING l_xml_table_size l_xml_table.
wrap the table containing the file into a stream
l_istream = l_streamfactory->create_istream_itable( table = l_xml_table
size = l_xml_table_size ).
Creating a document
l_document = l_ixml->create_document( ).
Create a Parser
l_parser = l_ixml->create_parser( stream_factory = l_streamfactory
istream = l_istream
document = l_document ).
Validate a document
IF pa_val EQ 'X'.
l_parser->set_validating( mode = if_ixml_parser=>co_validate ).
ENDIF.
Parse the stream
IF l_parser->parse( ) NE 0.
IF l_parser->num_errors( ) NE 0.
DATA: parseerror TYPE REF TO if_ixml_parse_error,
str TYPE string,
i TYPE i,
count TYPE i,
index TYPE i.
count = l_parser->num_errors( ).
WRITE: count, ' parse errors have occured:'.
index = 0.
WHILE index < count.
parseerror = l_parser->get_error( index = index ).
i = parseerror->get_line( ).
WRITE: 'line: ', i.
i = parseerror->get_column( ).
WRITE: 'column: ', i.
str = parseerror->get_reason( ).
WRITE: str.
index = index + 1.
ENDWHILE.
ENDIF.
ENDIF.
Process the document
IF l_parser->is_dom_generating( ) EQ 'X'.
PERFORM process_dom USING l_document.
ENDIF.
*& Form get_xml_table
FORM get_xml_table CHANGING l_xml_table_size TYPE i
l_xml_table TYPE STANDARD TABLE.
Local variable declaration
DATA: l_len TYPE i,
l_len2 TYPE i,
l_tab TYPE tsfixml,
l_content TYPE string,
l_str1 TYPE string,
c_conv TYPE REF TO cl_abap_conv_in_ce,
l_itab TYPE TABLE OF string.
l_filename = pa_file.
upload a file from the client's workstation
CALL METHOD cl_gui_frontend_services=>gui_upload
EXPORTING
filename = l_filename
filetype = 'BIN'
IMPORTING
filelength = l_xml_table_size
CHANGING
data_tab = l_xml_table
EXCEPTIONS
OTHERS = 19.
IF sy-subrc <> 0.
MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
ENDIF.
Writing the XML document to the screen
CLEAR l_str1.
LOOP AT l_xml_table INTO l_xml_line.
c_conv = cl_abap_conv_in_ce=>create( input = l_xml_line-data replacement = space ).
c_conv->read( IMPORTING data = l_content len = l_len ).
CONCATENATE l_str1 l_content INTO l_str1.
ENDLOOP.
l_str1 = l_str1+0(l_xml_table_size).
SPLIT l_str1 AT cl_abap_char_utilities=>cr_lf INTO TABLE l_itab.
WRITE: /.
WRITE: /' XML File'.
WRITE: /.
LOOP AT l_itab INTO l_str1.
REPLACE ALL OCCURRENCES OF cl_abap_char_utilities=>horizontal_tab IN
l_str1 WITH space.
WRITE: / l_str1.
ENDLOOP.
WRITE: /.
ENDFORM. "get_xml_table
*& Form process_dom
FORM process_dom USING document TYPE REF TO if_ixml_document.
DATA: node TYPE REF TO if_ixml_node,
iterator TYPE REF TO if_ixml_node_iterator,
nodemap TYPE REF TO if_ixml_named_node_map,
attr TYPE REF TO if_ixml_node,
name TYPE string,
prefix TYPE string,
value TYPE string,
indent TYPE i,
count TYPE i,
index TYPE i.
node ?= document.
CHECK NOT node IS INITIAL.
ULINE.
WRITE: /.
WRITE: /' DOM-TREE'.
WRITE: /.
IF node IS INITIAL. EXIT. ENDIF.
create a node iterator
iterator = node->create_iterator( ).
get current node
node = iterator->get_next( ).
loop over all nodes
WHILE NOT node IS INITIAL.
indent = node->get_height( ) * 2.
indent = indent + 20.
CASE node->get_type( ).
WHEN if_ixml_node=>co_node_element.
element node
name = node->get_name( ).
nodemap = node->get_attributes( ).
WRITE: / 'ELEMENT :'.
WRITE: AT indent name COLOR COL_POSITIVE INVERSE.
IF NOT nodemap IS INITIAL.
attributes
count = nodemap->get_length( ).
DO count TIMES.
index = sy-index - 1.
attr = nodemap->get_item( index ).
name = attr->get_name( ).
prefix = attr->get_namespace_prefix( ).
value = attr->get_value( ).
WRITE: / 'ATTRIBUTE:'.
WRITE: AT indent name COLOR COL_HEADING INVERSE, '=',
value COLOR COL_TOTAL INVERSE.
ENDDO.
ENDIF.
WHEN if_ixml_node=>co_node_text OR
if_ixml_node=>co_node_cdata_section.
text node
value = node->get_value( ).
WRITE: / 'VALUE :'.
WRITE: AT indent value COLOR COL_GROUP INVERSE.
ENDCASE.
advance to next node
node = iterator->get_next( ).
ENDWHILE.
ENDFORM. "process_dom
Any help would be highly apperciated.
regards,
Jessica SamPavel Vera,
With your example i tries doing the following .....
I tried to convert the data of XML file to internal table data. I am collecting the data in internal table to do goos recipt with that data.
Please find my XML file, ABAP pgm and XSLT pgm . I donu2019t know what I am missing I am not getting any output. I donu2019t know what is wrong please help me with this
Below is my XML file, My code and XSLT Program. In the below XML file I need to collect Vendor Number, Order Number, and Date tags which occur only once for one XML file.
I also need to collect the following tags from <Shipmentdetail>
<Shipmentdetail> has following child nodes and I need to collect them
TrackingNumber
Freight
Weight
ShipmentDate
ShipmentMethod
Need to collect to collect the following tags from <ProductInformation>
<ProductInformation> has following child nodes and I need to collect them
LineNumber
SKUNumber
OrderedQuantity
ShippedQuantity
UOM
The <Shipmentdetail> and <ProductInformation> are child nodes of <OrderShipment>
The <Shipmentdetail> occurs only ones but the <ProductInformation> can occur once or many times and will be dynamic and differs depening on the input file.
My XML file is as follows
<?xml version="1.0" encoding="iso-8859-1" ?>
- <ShipmentHeader>
<AccountID />
- <OrderShipment>
<VendorNumber>1000</VendorNumber>
<OrderNumber>P00009238</OrderNumber>
<OrderType>Stock</OrderType>
<Company />
<Division />
<Department />
<Date>20061120</Date>
<CartonCount>2</CartonCount>
<ShipAllProducts>No</ShipAllProducts>
- <ShipmentDetail>
<TrackingNumber>1ZR3W891PG47477811</TrackingNumber>
<Freight>000000010000</Freight>
<ShipmentDate>20061120</ShipmentDate>
<ShipmentMethod>UPS1PS</ShipmentMethod>
</ShipmentDetail>
- <ProductInformation>
<LineNumber>000000001</LineNumber>
<SKUNumber>110FR</SKUNumber>
<AdvSKUNumber>003 4518</AdvSKUNumber>
<SKUID />
<OrderedQuantity>00000001000000</OrderedQuantity>
<ShippedQuantity>00000001000000</ShippedQuantity>
<UOM>EA</UOM>
<Factor>1</Factor>
</ProductInformation>
- <ProductInformation>
<LineNumber>000000002</LineNumber>
<SKUNumber>938EN</SKUNumber>
<AdvSKUNumber>001 7294</AdvSKUNumber>
<SKUID />
<OrderedQuantity>00000000450000</OrderedQuantity>
<ShippedQuantity>00000000450000</ShippedQuantity>
<UOM>EA</UOM>
<Factor>1</Factor>
</ProductInformation>
- <CaseInformation>
<LineNumber>000000001</LineNumber>
<SKUNumber>110FR</SKUNumber>
<AdvSKUNumber>003 4518</AdvSKUNumber>
<SKUID />
<SSCCNumber>00000001668000002487</SSCCNumber>
<CaseQuantity>00000001000000</CaseQuantity>
<UOM>EA</UOM>
<Factor>1</Factor>
</CaseInformation>
<CaseInformation>
<LineNumber>000000001</LineNumber>
<SKUNumber>110FR</SKUNumber>
<AdvSKUNumber>003 4518</AdvSKUNumber>
<SKUID />
<SSCCNumber>00000001668000002487</SSCCNumber>
<CaseQuantity>00000001000000</CaseQuantity>
<UOM>EA</UOM>
<Factor>1</Factor>
</CaseInformation>
- </OrderShipment>
</ShipmentHeader>
My Program
TYPE-POOLS abap.
CONSTANTS gs_file TYPE string VALUE 'C:\temp\test.xml'.
* This is the structure for the data from the XML file
TYPES: BEGIN OF ts_shipment,
VendorNumber(10) TYPE n,
OrderNumber(20) TYPE n,
OrderType(8) TYPE c,
Date(8) TYPE c,
END OF ts_shipment.
TYPES: BEGIN OF ts_shipmentdetail,
TrackingNumber(30) TYPE n,
Freight(12) TYPE n,
Weight(14) TYPE n,
ShipmentDate(8) TYPE c,
ShipmentMethod(8) TYPE c,
END OF ts_shipmentdetail.
TYPES: BEGIN OF ts_productinformation,
LineNumber(9) TYPE n,
SKUNumber(20) TYPE c,
OrderedQuantity(14) TYPE n,
ShippedQuantity(14) TYPE n,
UOM(4) TYPE c,
END OF ts_productinformation.
* Table for the XML content
DATA: gt_itab TYPE STANDARD TABLE OF char2048.
* Table and work ares for the data from the XML file
DATA: gt_shipment TYPE STANDARD TABLE OF ts_shipment,
gs_shipment TYPE ts_shipment.
DATA: gt_shipmentdetail TYPE STANDARD TABLE OF ts_shipmentdetail,
gs_shipmentdetail TYPE ts_shipmentdetail.
DATA: gt_productinformation TYPE STANDARD TABLE OF ts_productinformation,
gs_productinformation TYPE ts_productinformation.
* Result table that contains references
* of the internal tables to be filled
DATA: gt_result_xml TYPE abap_trans_resbind_tab,
gs_result_xml TYPE abap_trans_resbind.
* For error handling
DATA: gs_rif_ex TYPE REF TO cx_root,
gs_var_text TYPE string.
* Get the XML file from your client
CALL METHOD cl_gui_frontend_services=>gui_upload
EXPORTING
filename = gs_file
CHANGING
data_tab = gt_itab
EXCEPTIONS
file_open_error = 1
file_read_error = 2
no_batch = 3
gui_refuse_filetransfer = 4
invalid_type = 5
no_authority = 6
unknown_error = 7
bad_data_format = 8
header_not_allowed = 9
separator_not_allowed = 10
header_too_long = 11
unknown_dp_error = 12
access_denied = 13
dp_out_of_memory = 14
disk_full = 15
dp_timeout = 16
not_supported_by_gui = 17
error_no_gui = 18
OTHERS = 19.
IF sy-subrc <> 0.
MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
ENDIF.
* Fill the result table with a reference to the data table.
* Within the XSLT stylesheet, the data table can be accessed with
* "ISHIPMENT".
GET REFERENCE OF gt_shipment INTO gs_result_xml-value.
gs_result_xml-name = 'ISHIPMENT'.
APPEND gs_result_xml TO gt_result_xml.
* Fill the result table with a reference to the data table.
* Within the XSLT stylesheet, the data table can be accessed with
* "ISHIPDET".
GET REFERENCE OF gt_shipmentdetail INTO gs_result_xml-value.
gs_result_xml-name = 'ISHIPDET'.
APPEND gs_result_xml TO gt_result_xml.
* Fill the result table with a reference to the data table.
* Within the XSLT stylesheet, the data table can be accessed with
* "IPRODDET".
GET REFERENCE OF gt_productinformation INTO gs_result_xml-value.
gs_result_xml-name = 'IPRODDET'.
APPEND gs_result_xml TO gt_result_xml.
* Perform the XSLT stylesheet
TRY.
CALL TRANSFORMATION z_xml_to_abap3
SOURCE XML gt_itab
RESULT (gt_result_xml).
CATCH cx_root INTO gs_rif_ex.
gs_var_text = gs_rif_ex->get_text( ).
MESSAGE gs_var_text TYPE 'E'.
ENDTRY.
* Writing the data from file for gt_shipment
*Collecting the Shipping Data from the XML file to internal table gt_shipment
*and writing the data to the screen
LOOP AT gt_shipment INTO gs_shipment.
WRITE: / 'VendorNumber:', gs_shipment-VendorNumber.
WRITE: / 'OrderNumber :', gs_shipment-OrderNumber.
WRITE: / 'OrderType :', gs_shipment-OrderType.
WRITE: / 'Date :', gs_shipment-Date.
WRITE : /.
ENDLOOP. "gt_shipment.
LOOP AT gt_shipmentdetail INTO gs_shipmentdetail.
WRITE: / 'TrackingNumber:', gs_shipmentdetail-TrackingNumber.
WRITE: / 'Freight :', gs_shipmentdetail-Freight.
WRITE: / 'Weight :', gs_shipmentdetail-Weight.
WRITE: / 'ShipmentDate :', gs_shipmentdetail-ShipmentDate.
* WRITE: / 'ShipmentMethod :' gs_shipmentdetail-ShipmentMethod
WRITE : /.
ENDLOOP. "gt_shipmentdetail.
LOOP AT gt_productinformation INTO gs_productinformation.
WRITE: / 'LineNumber:', gs_productinformation-LineNumber.
WRITE: / 'SKUNumber :', gs_productinformation-SKUNumber.
WRITE: / 'OrderedQuantity :', gs_productinformation-OrderedQuantity.
WRITE: / 'ShippedQuantity :', gs_productinformation-ShippedQuantity.
WRITE: / 'UOM :', gs_productinformation-UOM.
WRITE : /.
ENDLOOP. "gt_productinformation.
XSLT Program
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output encoding="iso-8859-1" indent="yes" method="xml" version="1.0"/>
<xsl:strip-space elements="*"/>
<xsl:template match="/">
<asx:abap xmlns:asx="http://www.sap.com/abapxml" version="1.0">
<asx:values>
<ISHIPMENT>
<xsl:apply-templates select="//OrderShipment"/>
</ISHIPMENT>
</asx:values>
</asx:abap>
</xsl:template>
<xsl:template match="OrderShipment">
<item>
<VENDORNUMBER>
<xsl:value-of select="VendorNumber"/>
</VENDORNUMBER>
<ORDERNUMBER>
<xsl:value-of select="OrderNumber"/>
</ORDERNUMBER>
<ORDERTYPE>
<xsl:value-of select="OrderType"/>
</ORDERTYPE>
<DATE>
<xsl:value-of select="Date"/>
</DATE>
</item>
</xsl:template>
<xsl:template match="/">
<asx:abap xmlns:asx="http://www.sap.com/abapxml" version="1.0">
<asx:values>
<ISHIPDET>
<xsl:apply-templates select="//OrderShipment/ShipmentDetail"/>
</ISHIPDET>
</asx:values>
</asx:abap>
</xsl:template>
<xsl:template match="ShipmentDetail">
<item>
<TRACKINGNUMBER>
<xsl:value-of select="TrackingNumber"/>
</TRACKINGNUMBER>
<FREIGHT>
<xsl:value-of select="Freight"/>
</FREIGHT>
<SHIPMENTDATE>
<xsl:value-of select="ShipmentDate"/>
</SHIPMENTDATE>
<SHIPMENTMETHOD>
<xsl:value-of select="ShipmentMethod"/>
</SHIPMENTMETHOD>
</item>
</xsl:template>
</xsl:transform> .
Any help is highly appreciated. If anyone encountered this situation before please let me know where i am going wrong in my XSLT transformation.
Any Help will be highly apppreciated. Thanks in advance
Regards,
Jessica Sam -
Need to insert values into a table from a XML file
Hi,
I'm an Oracle 9i/10g DBA with quite a few years experience, but I'm new to XML and dealing with it in database terms. I've been given a project that entails pulling XML values out of a file (or 100's of them) and storing them in the database so that they are searchable by end-users. The project is classified as secret so I'm unable to upload the specific XML or any info relating to the structire of the XML or the table I will use to insert the values into - sorry!! So, I've created an XML file with a similar structure to help people understand my predicament.
The end-users only need to search on a subset of the total amount of columns from the table I'll insert data into, although the XML file has a lot more, so I dont need to store the other values - but I will need to store the name of the XML file (or a pointer to it so I know what XML file a particular set of values belong to) in another column of the table along with its associated values.
I've been using the XMLTABLE function with some degree of success, although I had better succes using the XMLSEQUENCE function. However, I found out this is deprecated in 10g and replaced with XMLTABLE, so I guess it's better if I use this in case we ever need to upgrade to 11g.
The main problem I've been having is that some elements in the XML files have multiple values for the one record when all the other records are the same. In terms of storing this in the database, I guess it would mean inserting multiple rows in the table for each element where the value differs. Here is a dumbed down XML file similar to what I've got along with the other SQL I've used:
+<?xml version="1.0" encoding="UTF-8"?>+
+<House>+
+<Warehouse>+
+<WarehouseId>1</WarehouseId>+
+<WarehouseName>+
+<Town>Southlake</Town>+
+<State>Texas</State>+
+</WarehouseName>+
+<Building>Owned</Building>+
+<Area>25000</Area>+
+<Docks>2</Docks>+
+<DockType>Rear load</DockType>+
+<WaterAccess>true</WaterAccess>+
+<RailAccess>N</RailAccess>+
+<Parking>Street</Parking>+
+<VClearance>10</VClearance>+
+</Warehouse>+
+<Warehouse>+
+<WarehouseId>2</WarehouseId>+
+<WarehouseName>+
+<Town>Poole</Town>+
+<State>Dorset</State>+
+</WarehouseName>+
+<WarehouseName>+
+<Town>Solihull</Town>+
+<County>West Midlands</State>+
+</WarehouseName>+
+<Building>Owned</Building>+
+<Area>40000</Area>+
+<Docks>5</Docks>+
+<DockType>Rear load</DockType>+
+<WaterAccess>true</WaterAccess>+
+<RailAccess>N</RailAccess>+
+<Parking>Bay</Parking>+
+<VClearance>10</VClearance>+
+</Warehouse>+
+<Warehouse>+
+<WarehouseId>3</WarehouseId>+
+<WarehouseName>+
+<Town>Fleet</Town>+
+<County>Hampshire</County>+
+</WarehouseName>+
+<Building>Owned</Building>+
+<Area>10000</Area>+
+<Docks>1</Docks>+
+<DockType>Side load</DockType>+
+<WaterAccess>false</WaterAccess>+
+<RailAccess>N</RailAccess>+
+<Parking>Bay</Parking>+
+<VClearance>20</VClearance>+
+</Warehouse>+
+</House>+
CREATE TABLE xmltest OF XMLTYPE;
INSERT INTO xmltest
VALUES(xmltype(bfilename('XML_DIR', 'test.xml'), nls_charset_id('AL32UTF8')));
Consequently, I need to...
1) Retrieve the results from the XML file for all 3 warehouses where multiple values for the same sub-element are shown as 2 rowsthe result set. (I am guessing there will be 4 rows returned as warehouse sub-2 has 2 different elements for <WarehouseName>.
2) Build a case statement into the query so that regardless of the sub-element name (i.e State or County), it is returned into the 1 column, for instance County.
So, if I run a query similar to the following...
select y.WarehouseId, y.Town, y.County, y.Area
from xmltest x, xmltable('/House/Warehouse' .......
I would like to get results back like this...
ID Town County Area
1 Southlake Texas 25000
2 Poole Dorset 40000
2 Solihull West Midlands 40000
3 Fleet hampshire 10000
Sorry for the non-formatting but I hope this all makessense to someone out there with what I'm trying to do.
I appreciate any help whatsoever because, as i said before, I'm totally new to XML and trying to read the vast amount of information there is out there on XML is all a bit daunting.
Many thanks in advance,
Shaun.Hi again,
Thanks for keeping the post open for me. I've had a look at the post illustrating the XFileHandler package, and tried to alter it to make it fit with my XML files. To help explain things, my XML file looks like this:
<?xml version="1.0"?>
<!DOCTYPE CMF_Doc SYSTEM "CMF_Doc.dtd">
<House>
<Warehouse>
<WarehouseId>1</WarehouseId>
<WarehouseName>
<Town>Southlake</Town>
<State>Texas</State>
</WarehouseName>
<Building>Owned</Building>
<Area>25000</Area>
<Docks>2</Docks>
<DockType>Rear load</DockType>
<WaterAccess>true</WaterAccess>
<RailAccess>N</RailAccess>
<Parking>Street</Parking>
<VClearance>10</VClearance>
</Warehouse>
<Warehouse>House
<WarehouseId>2</WarehouseId>
<WarehouseName>
<Town>Poole</Town>
<State>Dorset</State>
</WarehouseName>
<WarehouseName>
<Town>Solihull</Town>
<County>West Midlands</County>
</WarehouseName>
<Building>Owned</Building>
<Area>40000</Area>
<Docks>5</Docks>
<DockType>Rear load</DockType>
<WaterAccess>true</WaterAccess>
<RailAccess>N</RailAccess>
<Parking>Bay</Parking>
<VClearance>10</VClearance>
</Warehouse>
<Warehouse>
<WarehouseId>3</WarehouseId>
<WarehouseName>
<Town>Fleet</Town>
<County>Hampshire</County>
</WarehouseName>
<Building>Owned</Building>
<Area>10000</Area>
<Docks>1</Docks>
<DockType>Side load</DockType>
<WaterAccess>false</WaterAccess>
<RailAccess>N</RailAccess>
<Parking>Bay</Parking>
<VClearance>20</VClearance>
</Warehouse>
</House>
<?xml version="1.0" encoding="UTF-8"?>
<House>
<Warehouse>
<WarehouseId>4</WarehouseId>
<WarehouseName>
<Town>Dallas</Town>
<State>Texas</State>
</WarehouseName>
<Building>Owned</Building>
<Area>25000</Area>
<Docks>2</Docks>
<DockType>Rear load</DockType>
<WaterAccess>true</WaterAccess>
<RailAccess>N</RailAccess>
<Parking>Street</Parking>
<VClearance>10</VClearance>
</Warehouse>
<Warehouse>
<WarehouseId>5</WarehouseId>
<WarehouseName>
<Town>Dorchester</Town>
<State>Dorset</State>
</WarehouseName>
<WarehouseName>
<Town>Solihull</Town>
<County>West Midlands</County>
</WarehouseName>
<Building>Owned</Building>
<Area>40000</Area>
<Docks>5</Docks>
<DockType>Rear load</DockType>
<WaterAccess>true</WaterAccess>
<RailAccess>N</RailAccess>
<Parking>Bay</Parking>
<VClearance>10</VClearance>
</Warehouse>
<Warehouse>
<WarehouseId>6</WarehouseId>
<WarehouseName>
<Town>Farnborough</Town>
<County>Hampshire</County>
</WarehouseName>
<Building>Owned</Building>
<Area>10000</Area>
<Docks>1</Docks>
<DockType>Side load</DockType>
<WaterAccess>false</WaterAccess>
<RailAccess>N</RailAccess>
<Parking>Bay</Parking>
<VClearance>20</VClearance>
</Warehouse>
</House>
<?xml version="1.0" encoding="UTF-8"?>
<House>
<Warehouse>
<WarehouseId>7</WarehouseId>
<WarehouseName>
<Town>Southlake</Town>
<State>Texas</State>
</WarehouseName>
<Building>Owned</Building>
<Area>25000</Area>
<Docks>2</Docks>
<DockType>Rear load</DockType>
<WaterAccess>true</WaterAccess>
<RailAccess>N</RailAccess>
<Parking>Street</Parking>
<VClearance>10</VClearance>
</Warehouse>
<Warehouse>
<WarehouseId>8</WarehouseId>
<WarehouseName>
<Town>Bournemouth</Town>
<State>Dorset</State>
</WarehouseName>
<WarehouseName>
<Town>Shirley</Town>
<County>West Midlands</County>
</WarehouseName>
<Building>Owned</Building>
<Area>30000</Area>
<Docks>5</Docks>
<DockType>Rear load</DockType>
<WaterAccess>true</WaterAccess>
<RailAccess>N</RailAccess>
<Parking>Bay</Parking>
<VClearance>10</VClearance>
</Warehouse>
<Warehouse>
<WarehouseId>9</WarehouseId>
<WarehouseName>
<Town>Clapham</Town>
<County>London</County>
</WarehouseName>
<Building>Owned</Building>
<Area>10000</Area>
<Docks>1</Docks>
<DockType>Side load</DockType>
<WaterAccess>false</WaterAccess>
<RailAccess>N</RailAccess>
<Parking>Bay</Parking>
<VClearance>20</VClearance>
</Warehouse>
</House>And the XFilehandler package looks like this (I'm just trying to do a simple select only on WarehouseId & WaterAccess for the time being to keep things simple):
create or replace package XFileHandler as
TYPE TRECORD IS RECORD (
WID NUMBER(2)
, WACCESS VARCHAR2(5)
type TRecordTable is table of TRecord;
function getRows (p_directory in varchar2, p_filename in varchar2) return TRecordTable pipelined;
end;
create or replace package body XFileHandler is
function getRows (p_directory in varchar2, p_filename in varchar2)
return TRecordTable pipelined
is
nb_rec number := 1;
tmp_xml clob;
tmp_file clob;
rec TRecord;
begin
DBMS_LOB.CREATETEMPORARY(TMP_FILE, TRUE);
tmp_file := dbms_xslprocessor.read2clob(p_directory, p_filename);
LOOP
tmp_xml := regexp_substr(tmp_file, '<\?xml[^?]+\?>\s*<([^>]+)>.*?</\1>', 1, nb_rec, 'n');
exit when length(tmp_xml) = 0;
--dbms_output.put_line(tmp_rec);
nb_rec := nb_rec + 1;
select y.WID, y.WACCESS
into rec.WID, rec.WACCESS
from xmltable('/House' passing xmltype(tmp_xml)
columns WID NUMBER(2) PATH 'Warehouse/WarehouseId',
WACCESS VARCHAR2(5) PATH 'WaterAccess') y;
pipe row ( rec );
end loop;
dbms_lob.freetemporary(tmp_file);
return;
end;
end;Now, when I run the query:
select * from table(XFileHandler.getRows('XML_DIR', 'XFileHandler_test.xml'));I get the error: ORA-00600: internal error code, arguments: [17285], [0x5CFE8DC8], [4], [0x45ABE1C8], [], [], [], []
I had a look in the dump file for anything obvious, but nothing really stands out. Is there anything obvious in my code that I'm missing or something else which you may think could be causing this error, e.g in the regular expression regexp_substr?
Many thanks,
Shaun. -
How to create and modify an XML file from an Oracle Form
I would like to build an Oracle Form to maintain a small XML file in the file system (i.e. Not in Oracle database but in the operating system).
I would like the Form to display existing values from the XML file and the user can update and save content back to the XML file.
Can any one tell me how this can be done? Thanks.Does Forms 9i provide any XML Parser Functions?
Can I insert the XML file into a table column by inserting XML using the XSU Front End rather than using TEXT_IO to maintain the XML file directly?
Can I use XSU PL/SQL API in Forms to retrieve and modify XML values?
Any help is appreciated. -
Inserting parent /child records from a xml file ...
XML file pasted below:
I have loaded the xml file into a table called xml_demo which has a column xml_data of type xmltype.
The select for parent record is as follows and it works:
INSERT INTO balit_submissions (balitdoc, documentversion, datetime_from,job_id, status,creation_datetime)
(SELECT 'MOL'
,to_number(extract(x.xml_data,'/MolDocument/DocumentVersion/@v'))
,to_date(substr(extract(x.xml_data,'/MolDocument/ValidTimeInterval/@v'),1,16),
'yyyy-mm-dd"T"hh24:mi')
,123456
,'CREATED',
NULL
FROM xml_DEMO x WHERE
existsnode(x.xml_data,'/MolDocument/DocumentIdentification[@v="MOL_20100331_1500_1600"]') = 1)
Having problem creating child records. From this file I expect to create 3 records.
insert into balit_energy_blocks
SO_ID,
DATETIME_FROM,
DIRECTION,
BLOCK_NUMBER,
ENERGY,
LAST_SUBMIT_DATETIME,
PRICE_POUNDS,
PRICE_EUROS,
BALIT_REF,
STATUS,
LAST_EDIT_DATETIME,
MOL_REASON,
ACQUIRING_SO_AREA)
(SELECT 'RTE'
,to_date(substr(extract(x.xml_data,'/MolDocument/ValidTimeInterval/@v'),1,16),
'yyyy-mm-dd"T"hh24:mi')
,DECODE(extract(x.xml_data,'/MolDocument/MolTimeSeries/Direction/@v'),'AO1','Up','Down')
,to_number(substr(extract(x.xml_data,'/MolDocument/MolTimeSeries/ContractIdentification/@v'),19))
,to_number(extract(x.xml_data,'/MolDocument/MolTimeSeries/Period/Interval/EnergyPrice/@v'))
,sysdate
,null -- price pounds
,null -- price euro
,extract(x.xml_data,'/MolDocument/MolTimeSeries/ContractIdentification/@v')
,'SUBMITTED'
,'A96'
,NULL -- acquiring area
,sysdate
FROM xml_DEMO x WHERE
existsnode(x.xml_data,'/MolDocument/DocumentIdentification[@v="MOL_20100331_1500_1600"]') = 1)
For example, there are 3 ContractIdentification tags. Example of 1:
<ContractIdentification v="RTE_20100331_1500_16"/>
I was expecting this select to pluck the last number from this string. In this case 16.
The select was:
to_number(substr(extract(x.xml_data,'/MolDocument/MolTimeSeries/ContractIdentification/@v'),19))
The result I got was:
16RTE_20100331_1500_20NG_20100331_1500_6
All contractident values are concatnated and returns from position 19 onwards.
Can anyone help me to extract the last number from each ContractIdentification tag value and to create the 3 records
Thanks
James Sathiaraj
<?xml version="1.0" encoding="UTF-8"?>
<MolDocument DtdVersion="3" DtdRelease="0">
<DocumentIdentification v="MOL_20100331_1500_1600"/>
<DocumentVersion v="1"/>
<DocumentType v="A43"/>
<SenderIdentification codingScheme="A01" v="17X100Z100Z0001H"/>
<SenderRole v="A35"/>
<ReceiverIdentification codingScheme="A01" v="10XFR-RTE------Q"/>
<ReceiverRole v="A04"/>
<CreationDateTime v="2010-03-31T14:10:00Z"/>
<ValidTimeInterval v="2010-03-31T15:00Z/2010-03-31T16:00Z"/>
<Domain codingScheme="A01" v="10YDOM-1001A001A"/>
<MolTimeSeries>
<ContractIdentification v="RTE_20100331_1500_16"/>
<ResourceProvider codingScheme="A01" v="10XFR-RTE------Q"/>
<AcquiringArea codingScheme="A01" v="17Y100Z100Z00013"/>
<ConnectingArea codingScheme="A01" v="10YFR-RTE------C"/>
<AuctionIdentification v="AUCTION_20100331_1500_1600"/>
<BusinessType v="A10"/>
<BidTimeInterval v="2010-03-31T15:00Z/2010-03-31T16:00Z"/>
<MeasureUnitQuantity v="MAW"/>
<Currency v="EUR"/>
<MeasureUnitPrice v="MWH"/>
<Direction v="A02"/>
<MinimumActivationQuantity v="50"/>
<Status v="A06"/>
<Period>
<TimeInterval v="2010-03-31T15:00Z/2010-03-31T16:00Z"/>
<Resolution v="PT60M"/>
<Interval>
<Pos v="1"/>
<Qty v="50"/>
<EnergyPrice v="50.45"/>
</Interval>
</Period>
</MolTimeSeries>
<MolTimeSeries>
<ContractIdentification v="RTE_20100331_1500_20"/>
<ResourceProvider codingScheme="A01" v="10XFR-RTE------Q"/>
<AcquiringArea codingScheme="A01" v="17Y100Z100Z00013"/>
<ConnectingArea codingScheme="A01" v="10YFR-RTE------C"/>
<AuctionIdentification v="AUCTION_20100331_1500_1600"/>
<BusinessType v="A10"/>
<BidTimeInterval v="2010-03-31T15:00Z/2010-03-31T16:00Z"/>
<MeasureUnitQuantity v="MAW"/>
<Currency v="EUR"/>
<MeasureUnitPrice v="MWH"/>
<Direction v="A02"/>
<MinimumActivationQuantity v="50"/>
<Status v="A06"/>
<Period>
<TimeInterval v="2010-03-31T15:00Z/2010-03-31T16:00Z"/>
<Resolution v="PT60M"/>
<Interval>
<Pos v="1"/>
<Qty v="50"/>
<EnergyPrice v="50.48"/>
</Interval>
</Period>
</MolTimeSeries>
<MolTimeSeries>
<ContractIdentification v="NG_20100331_1500_6"/>
<ResourceProvider codingScheme="A01" v="10X1001A1001A515"/>
<AcquiringArea codingScheme="A01" v="17Y100Z100Z00013"/>
<ConnectingArea codingScheme="A01" v="10YGB----------A"/>
<AuctionIdentification v="AUCTION_20100331_1500_1600"/>
<BusinessType v="A10"/>
<BidTimeInterval v="2010-03-31T15:00Z/2010-03-31T16:00Z"/>
<MeasureUnitQuantity v="MAW"/>
<Currency v="EUR"/>
<MeasureUnitPrice v="MWH"/>
<Direction v="A01"/>
<MinimumActivationQuantity v="50"/>
<Status v="A06"/>
<Period>
<TimeInterval v="2010-03-31T15:00Z/2010-03-31T16:00Z"/>
<Resolution v="PT60M"/>
<Interval>
<Pos v="1"/>
<Qty v="50"/>
<EnergyPrice v="17.0"/>
</Interval>
</Period>
</MolTimeSeries>
</MolDocument>Hi,
The result I got was:
16RTE_20100331_1500_20NG_20100331_1500_6In the query you tried, you access a single record so you can't expect to get three rows "magically". The EXTRACT function just works as expected, it extracts the requested nodes, but the result is still an XML fragment (a scalar value).
In order to achieve your goal, you have to break the MolTimeSeries sequence into relational rows.
Two similar solutions are possible, XMLTable (10gR2 and up) or Table/XMLSequence.
In your other post you mentioned db version 10.1, so I guess we'll go with XMLSequence :
SELECT 'RTE'
,to_date(substr(extractvalue(x.xml_data,'/MolDocument/ValidTimeInterval/@v'),1,16),'yyyy-mm-dd"T"hh24:mi')
,decode(extractvalue(x2.column_value,'/MolTimeSeries/Direction/@v'),'A01','Up','Down')
,to_number(regexp_substr(extractvalue(x2.column_value,'/MolTimeSeries/ContractIdentification/@v'),'\d+$'))
,to_number(extractvalue(x2.column_value,'/MolTimeSeries/Period/Interval/EnergyPrice/@v'))
,sysdate
,null
,null
,extractvalue(x2.column_value,'/MolTimeSeries/ContractIdentification/@v')
,'SUBMITTED'
,'A96'
,null
,sysdate
FROM xml_demo x,
table(
xmlsequence(
extract(x.xml_data, '/MolDocument/MolTimeSeries')
) x2
WHERE existsnode(x.xml_data,'/MolDocument/DocumentIdentification[@v="MOL_20100331_1500_1600"]') = 1;Please also note the use of REGEXP_SUBSTR instead of the regular SUBSTR because it didn't work for "NG_20100331_1500_6".
Hope that helps.
Edited by: odie_63 on 24 juin 2010 21:18 - added regexp comment -
Hi, extract data from xml file and insert into another exiting xml file
i am searching code to extract data from xml file and insert into another exiting xml file by a java program. I understood it is easy to extract data from a xml file, and how ever without creating another xml file. We want to insert the extracted data into another exiting xml file. Suggestions?
1st xml file which has two lines(text1.xml)
<?xml version="1.0" encoding="iso-8859-1"?>
<xs:PrintDataRequest xmlns:xs="http://com.unisys.com/Anid"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://com.unisys.com/Anid file:ANIDWS.xsd">
<xs:Person>
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://com.unisys.com/Anid file:ANIDWS.xsd">
These two lines has to be inserted in the existing another xml(text 2.xml) file(at line 3 and 4)
Regards,
bubblyJadz_Core wrote:
RandomAccessFile? If you know where you want to insert it.Are you sure about this? If using this, the receiving file would have to have bytes inserted that exactly match the number of bytes replaced. I'm thinking that you'll likely have to stream through the second XML with a SAX parser and copy information (or insert new information) as you stream with an XML writer of some sort. -
Extract data from xml file and insert into another exiting xml fil
hello,
i am searching extract data from xml file and insert into another exiting xml file by a java program. I understood it is easy to extract data from a xml file, and how ever without creating another xml file. We want to insert the extracted data into another exiting xml file. Suggestions?
Regards,
ZhuozhiIf the files are small, you can load the target file in a DOM document, insert the data from the source file and persist the DOM.
If the files are large, you probably want to use a StAX or SAX. -
Right, so I have a windowsform with lots of Textboxes, where the user can type in Information, and then hit "Save", once its saved it goes into a sortof XML Format
<?xml version="1.0" encoding="utf-8"?>
<!--Database-->
<Case>
<Person>l<Driver></Driver><License-Holder></License-Holder><Address></Address><Phone></Phone><Date-of-Birth></Date-of-Birth><Registration></Registration>
Like that.
Now, on my Startup Form (The main form) there is a Listview that I gave the name Objectlist1. This list displays ANY file located in a specific folder on my computer. This is also where the Saved files appear.
The list also updates every 5th second so after you save it appears quickly.
Now, the Files are saved using the content or Value of the first Textbox:
Dim XmlWrt As XmlWriter = XmlWriter.Create("C:\Users\USER\Desktop\TESTFOLDER\" + Firsttextbox.Text, settings)
So it appears in the folder and on the list with the value inserted in the first Textbox.
My problem comes when I want to load this back (Or reverse the function if you will)
Where I can go to the Objectlist1/Listview, either doubleclick a file or Mark a file, and hit my button "Retrieve"
I want the Form where you could input all the values to show - which it does
And the information from the XML/File saved to appear where it once was typed or inserted.
Here is an example of the code used to save the values from the Textboxes;
Private Sub Savebutton_Click(sender As Object, e As EventArgs) Handles Savebutton.Click
If IO.File.Exists(Pholderbox.Text) = False Then
Dim settings As New XmlWriterSettings()
settings.Indent = True
Dim XmlWrt As XmlWriter = XmlWriter.Create("C:\Users\USER\Desktop\TESTFOLDER\" + Pholderbox.Text, settings)
With XmlWrt
' Write the Xml declaration.
.WriteStartDocument()
' CLIENT
' Write a comment.
.WriteComment("Database")
' Write the root element.
.WriteStartElement("Case")
' Start our first person.
.WriteStartElement("Person")
.WriteString(Textbox1.Text)
' The person nodes.
.WriteStartElement("Driver")
.WriteString(Textbox2.Text)
.WriteEndElement()
I've tried multiple codesamples but they all give either "XML Not found" or such Overloads.
This is the current code I used when trying to make it work
Private Function ReadSettingsXML(ByVal path As String) As MySettings # On Debug It marks here and tells me it wasn't found.
Dim thisSettingsInfo As New MySettings
If My.Computer.FileSystem.FileExists(Objectlist1.SelectedItems.ToString) Then
Dim settingsInfo = XElement.Load(Objectlist1.SelectedItems.ToString)
If settingsInfo IsNot Nothing Then
For Each mainGroup As XElement In settingsInfo.Elements
If mainGroup.Name = "<Database>" AndAlso mainGroup.HasElements Then
For Each subGroup As XElement In mainGroup.Elements
If subGroup.Name = "<Person>" Then
thisSettingsInfo.Textbox1 = subGroup.Value
ElseIf subGroup.Name = "<Driver>" Then
thisSettingsInfo.Textbox2 = subGroup.Value
ElseIf subGroup.Name = "<Address>" Then
thisSettingsInfo.Textbox3 = subGroup.Value
End If
Next
End If
Next
Else
thisSettingsInfo = Nothing
Throw New Exception("The settings XML file is corrupt and cannot be read.")
End If
Else
thisSettingsInfo = Nothing
Throw New Exception("The settings XML file could not be located.")
End If
Return thisSettingsInfo
End Function
Private Sub LoadXML_Click(sender As Object, e As EventArgs) Handles LoadXML.Click
Dim settings As New MySettings
settings = ReadSettingsXML(Objectlist1.SelectedItems.ToString)
If settings IsNot Nothing Then
Dim sb As New System.Text.StringBuilder
With settings
Caseworker.Textbox1.Text = .Person
Caseworker.Textbox2.Text = .Driver
Caseworker.Textbox3.Text = .Address
End With
End If
End Sub
Also, the "Caseworker" is the form where all the textboxes are located.
Been stuck on this for two working days, so any help is highly appreciated
Codesamples are also highly welcome so I can see what the heck you did and find and answer to my problems.I found a code that might be close to what I'm looking, but as of this code used here, it looks for a static document that already exist and is located in the code.
See this one here, checks for the XML file, and since I can't link one program to 1 file, when its gonna have and use 100's of files.
If (IO.File.Exists("MyXML.xml")) Then
Same here with the static document.
Dim document As XmlReader = New XmlTextReader("MyXML.xml")
While (document.Read())
Dim type = document.NodeType
'if node type was element
If (type = XmlNodeType.Element) Then
If (document.Name = "FirstName") Then
TextBox1.Text = document.ReadInnerXml.ToString()
End If
If (document.Name = "LastName") Then
TextBox2.Text = document.ReadInnerXml.ToString()
End If
End If
End While
Am I at least close here, people?
Can anyone help with the now critical issue I got?
I basically need to change these two;
If (IO.File.Exists("MyXML.xml")) Then
Same here with the static document.
Dim document As XmlReader = New XmlTextReader("MyXML.xml")
To whatever value, so they read from the file SELECTED in my Listview
Cos the program saves files according to the info inserted in textboxes, so it can have whatever name you can think of, I need the program to "find and load" that file, once its selected, and then once I hit Retrieve or LOAD or whatever button, it
injects the info from the File to the correct Textboxes.
And I think this will work to get the info in the right boxes;
If (document.Name = "FirstName") Then
TextBox1.Text = document.ReadInnerXml.ToString()
End If
If (document.Name = "LastName") Then
TextBox2.Text = document.ReadInnerXml.ToString()
Any good advise? I'm stranded here. -
How can I read an XML string that's not from an XML file?
I've got a script I'm trying to setup that communicates over a socket to retrieve different directions from a custom built Java program. The Java program listens to requests from the Adobe scripting engine (in my case it's a Photoshop script) on a socket and immediately responds with the next set of directions. These directions are currently in XML format. The issue I'm having is that I can't parse the XML data since it's entered into a new XML object from a string rather than being read from a file. Even without the socket code, you can see the issue by doing the following:
var xml = new XML("<test><data>hey!</data></test>");
alert(xml.test.data);
alert(xml);
The first alert "should" return "hey!" (without quotes, of course), but it doesn't, while the second alert returns what you would expect it to:
<test>
<data>hey!</data>
</test>
It works fine if read from an XML file, but from a string, like shown above, it just presents an empty alert box when attempting to access "xml.test.data". Any ideas on how to fix this issue? Can it be fixed? Has it been fixed in newer versions (I'm currently using CS4)?
Thanks in advance for any help!Duh... found my error... I was attempting to access the data by referencing the created "root" element. Since <test> is the very first element tag, it's setup as the root element, which you don't need to reference. Changing the alert to alert(xml.data); fixed it.
Now I just feel dumb, lol... -
How to populate a form from an xml file with multiple records
I want to be able to create a single form that will add pages as needed based upon the number of records being imported from an xml file.
I have an IRS form that does this exactly, but I do not know how to re-create it. I entered data into the form, then exported that data to xml. Then I opened that xml file in excel and added more records (this is just an easy way to manage the xml data in a tabular form). Then I import the changed xml file into the IRS form and it adds as many pages as I have records. Perfect! Unfortunately, I cannot edit the form to examine the technique. It does not appear to be relying upon any additional local javascript files. It does use an 'add page' button which may suggest the form is using the template .spawn() technique, but when I try that in my own form, it gives me unique field names for each page which are then not consistent with the xml data. Hopefully someone can help me understand what I am missing.did you want
<record>0
<data>"11.97.23.174/32"
<record>address <data>
<record>address <data>
<record>subnet <data>
<record>ip <data>"10.97.23.174"</data></record>
</data></record>
</data></record>
</data></record>
</data></record>
or
<record>0
<data>"11.97.23.174/32"
<record>address <data>
<record>address <data>
<record>subnet <data>
<record>ip <data>"10.97.23.174"</data></record>
Maybe you are looking for
-
An iPhone Burned My Girlfriend... And Now Will Not Charge/Sync
So last week my girlfriend's iPhone 3gs did something new. She had just plugged it into the charger - the one that came with the phone when she purchased it - and plugged the charger into a wall outlet. My iPhone charger occupied the other socket. Wi
-
Hello, i've created a Theme and assign it to all users in main_rules (System Administration > Portal Display > Desktops & Display rules > Portal Administrators > Super Administrators). But I've enter a wrong path (one mistake), saved it and loged ou
-
HP Laserjet 1300 cabable of wireless printing?
Is the HP Laserjet 1300 cabable of wireless printing? Is there a part available that will convert the serial port and plug directly into my router?
-
Hi This has taken me the best part of a day and I've gotten nowhere, so I'd be really grateful for some help. I'm developing my first J2EE (1.3.1) (SE 1.4.2) app from home, in Linux (RH9), and I have a bug I can't solve. I'd like to know how you'd go
-
HI Pl tell me how to create number ranges for different order types , planed orders , task list group when iam creating routing and rate routing(exterinal and internal ) pl tell me step by step regards Baswaraj