loop / Extract nodes from clob xml column in oracle pl sql - sql

I have this xml content stored in a clob column of a table, I have to loop through the "molecule" nodes under the "reactantList" node,and store each "molecule" node into another table containing a list of molecules,
Any help please?
I tried with xmltype, xmlsequence, xmltable etc but did not work, I also have to specify the namespace "xmlns=.." somewhere as an argument to xmltype I think, to be able to make it work...
<cml xmlns="http://www.chemaxon.com" version="ChemAxon file format v20.20.0, generated by vunknown" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.chemaxon.com http://www.chemaxon.com/marvin/schema/mrvSchema_20_20_0.xsd">
<MDocument>
<MChemicalStruct>
<reaction>
<arrow type="DEFAULT" x1="-8.022119140625" y1="0.8333333333333334" x2="-3.5637858072916657" y2="0.8333333333333334" />
<reactantList>
<molecule molID="m1">
<atomArray>
<atom id="a1" elementType="C" x2="-13.938333333333334" y2="0.7083333333333333" />
<atom id="a2" elementType="O" x2="-15.478333333333333" y2="0.7083333333333333" lonePair="2" />
</atomArray>
<bondArray>
<bond id="b1" atomRefs2="a1 a2" order="1" />
</bondArray>
</molecule>
<molecule molID="m2">
<atomArray>
<atom id="a1" elementType="O" x2="-9.897119140624998" y2="0.8333333333333333" mrvValence="0" lonePair="3" />
</atomArray>
<bondArray />
</molecule>
</reactantList>
<agentList />
<productList />
</reaction>
</MChemicalStruct>
<MReactionSign toption="NOROT" fontScale="14.0" halign="CENTER" valign="CENTER" autoSize="true" id="o1">
<Field name="text">
<![CDATA[{D font=SansSerif,size=18,bold}+]]>
</Field>
<MPoint x="-11.730452473958332" y="0.6666666666666666" />
<MPoint x="-11.217119140624998" y="0.6666666666666666" />
<MPoint x="-11.217119140624998" y="1.18" />
<MPoint x="-11.730452473958332" y="1.18" />
</MReactionSign>
</MDocument>
</cml>

You can use:
INSERT INTO molecules (molecule)
SELECT x.molecule
FROM table_name t
CROSS APPLY XMLTABLE(
XMLNAMESPACES(
'http://www.w3.org/2001/XMLSchema-instance' AS "xsi",
DEFAULT 'http://www.chemaxon.com'
),
'/cml/MDocument/MChemicalStruct/reaction/reactantList/molecule'
PASSING XMLTYPE(t.xml)
COLUMNS
molecule XMLTYPE PATH '.'
) x
db<>fiddle here

Related

extracting json tag value available within xml

From the below XML log, I have requirement to extract phoneNumber only <json:string name="phoneNumber">9480562628</json:string>. Can someone help in this??
<Input>
<Header>
<User-Agent>android;11;4.27.0;samsung_SM-A205F</User-Agent>
<Date>Sun, 09 Oct 2022 21:59:08 GMT</Date>
<Username />
<UserInfo />
<Location>1wIRSNscfkI0qragmfshMiG189qgAf/PumlP3DTbgN4=</Location>
<AAAUN>SFASJNF3U6375H7D1Y4XWJDZ</AAAUN>
<Authorization>WS androidDove:ri6/G20ZNX+bsNyX8GUEB4vSMS4=</Authorization>
<h>test</h>
<Accept-Language>en</Accept-Language>
<Test>false</Test>
<Content-Type>application/json; charset=UTF-8</Content-Type>
<Content-Length>75</Content-Length>
<Host>com.in</Host>
<Accept-Encoding>gzip</Accept-Encoding>
<X-Forwarded-For>0.0.0.0, 0.0.0.0</X-Forwarded-For>
<X-APIRP-ID>0.0.0.0</X-APIRP-ID>
<Via>1.1 69WC0-</Via>
<X-Client-IP>0.0.0.0.</X-Client-IP>
<X-Global-Transaction-ID>RU44D1I3S40ZBVLMQHHUZSB1QOH1HEWO700LZQLB5WR8IGZYU4</X-Global-Transaction-ID>
</Header>
<X />
<URI>/esb/crs2/public/Login</URI>
<ServiceName>PUBLICPOSTOTPLOGIN</ServiceName>
<PrimaryKey />
<Parameters>
<Parameter1 />
<Parameter2 />
<Parameter3 />
<Parameter4 />
</Parameters>
<Body>
<json:object xmlns:json="http://www.ibm.com/" xmlns:xsi="http://www.w3.org/" xsi:schemaLocation="http://www.datapower.com">
<json:string name="phoneNumber">9480562628</json:string>
</json:object>
</Body>
<standardRule>Y</standardRule>
<TRANSACTION_ID>SFASJNF3U6375H7D1Y4XWJDZ</TRANSACTION_ID>
<TRANSACTION_NAME>Login</TRANSACTION_NAME>
<JSON_Body>{ "phoneNumber":"9480562628" }</JSON_Body>
</Input>
Expected Result:
9480562628
This statement got the result as expected. :)
extractvalue(xmltype(x.xml_request), '(/Input//phoneNumber)[1]/text()')
|| ' '|| extractvalue(xmltype(x.xml_request), '(/Input/Body//*[#name="phoneNumber"])[1]/text()') AS "phoneNumber_"
Use XMLTABLE and specify the XMLNAMESPACES:
SELECT x.*
FROM table_name t
CROSS APPLY XMLTABLE(
XMLNAMESPACES('http://www.ibm.com/' AS "json", 'http://www.w3.org/' AS "xsi"),
'/Input'
PASSING XMLTYPE(t.xml)
COLUMNS
phonenumber VARCHAR2(20) PATH './Body/json:object/json:string[#name="phoneNumber"]'
) x
Which, for your sample data:
CREATE TABLE table_name (xml CLOB);
INSERT INTO table_name (xml) VALUES ('<Input>
<Header>
<User-Agent>android;11;4.27.0;samsung_SM-A205F</User-Agent>
<Date>Sun, 09 Oct 2022 21:59:08 GMT</Date>
<Username />
<UserInfo />
<Location>1wIRSNscfkI0qragmfshMiG189qgAf/PumlP3DTbgN4=</Location>
<AAAUN>SFASJNF3U6375H7D1Y4XWJDZ</AAAUN>
<Authorization>WS androidDove:ri6/G20ZNX+bsNyX8GUEB4vSMS4=</Authorization>
<h>test</h>
<Accept-Language>en</Accept-Language>
<Test>false</Test>
<Content-Type>application/json; charset=UTF-8</Content-Type>
<Content-Length>75</Content-Length>
<Host>com.in</Host>
<Accept-Encoding>gzip</Accept-Encoding>
<X-Forwarded-For>0.0.0.0, 0.0.0.0</X-Forwarded-For>
<X-APIRP-ID>0.0.0.0</X-APIRP-ID>
<Via>1.1 69WC0-</Via>
<X-Client-IP>0.0.0.0.</X-Client-IP>
<X-Global-Transaction-ID>RU44D1I3S40ZBVLMQHHUZSB1QOH1HEWO700LZQLB5WR8IGZYU4</X-Global-Transaction-ID>
</Header>
<X />
<URI>/esb/crs2/public/Login</URI>
<ServiceName>PUBLICPOSTOTPLOGIN</ServiceName>
<PrimaryKey />
<Parameters>
<Parameter1 />
<Parameter2 />
<Parameter3 />
<Parameter4 />
</Parameters>
<Body>
<json:object xmlns:json="http://www.ibm.com/" xmlns:xsi="http://www.w3.org/" xsi:schemaLocation="http://www.datapower.com">
<json:string name="phoneNumber">9480562628</json:string>
</json:object>
</Body>
<standardRule>Y</standardRule>
<TRANSACTION_ID>SFASJNF3U6375H7D1Y4XWJDZ</TRANSACTION_ID>
<TRANSACTION_NAME>Login</TRANSACTION_NAME>
<JSON_Body>{ "phoneNumber":"9480562628" }</JSON_Body>
</Input>'
);
Outputs:
PHONENUMBER
9480562628
fiddle

Extracting data from XML Array using SQL

I have the following XML and would like to extract the PrimaryTeams, SecondaryTeams and OverflowTeams arrays from this and either have them comma separated or one per row.
I have the following xml:
declare #xml xml
set #xml = '<SimpleStrategy xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/Synthesys.Switch.ACD">
<Id>00000000-0000-0000-0000-000000000000</Id>
<Name>Default</Name>
<AcceptedCLIs xmlns:d2p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<d2p1:string>07811353995</d2p1:string>
</AcceptedCLIs>
<ActiveHours>
<FridayEnd />
<FridayStart />
<MondayEnd />
<MondayStart />
<SaturdayEnd />
<SaturdayStart />
<SundayEnd />
<SundayStart />
<ThursdayEnd />
<ThursdayStart />
<TuesdayEnd />
<TuesdayStart />
<UseIndividualWeekDays>false</UseIndividualWeekDays>
<WednesdayEnd />
<WednesdayStart />
<WeekdayEnd />
<WeekdayStart />
</ActiveHours>
<AgentUserName />
<AllowRouteDuringFinalMessage>false</AllowRouteDuringFinalMessage>
<CRMPrefix />
<DirectDDIMessage />
<DirectDDIPassThrough>false</DirectDDIPassThrough>
<EmergencyBusyBack>false</EmergencyBusyBack>
<EmergencyDivertNumber />
<EmergencyWavFile />
<FinallyDivertNumber />
<FinallyDrop>true</FinallyDrop>
<FinallyMessageFile />
<MaximumQueueLength>0</MaximumQueueLength>
<MaximumQueueWait>0</MaximumQueueWait>
<MinimumRingTime>4000</MinimumRingTime>
<MusicOnHold />
<MusicWhileWaiting />
<NumberOfRings>2</NumberOfRings>
<OutOfHoursDivertNumber />
<OutOfHoursDrop>true</OutOfHoursDrop>
<OutOfHoursMessage />
<OverflowMessage />
<OverflowTeams xmlns:d2p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays" />
<PrimaryTeams xmlns:d2p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<d2p1:int>3</d2p1:int>
<d2p1:int>1</d2p1:int>
</PrimaryTeams>
<Priority>1</Priority>
<RecordAgent>false</RecordAgent>
<RecordCall>true</RecordCall>
<RecordCustomer>false</RecordCustomer>
<RegulatoryMessage>Default.wav</RegulatoryMessage>
<SecondaryOverflowMessage />
<SecondaryTeams xmlns:d2p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays" />
<SendBusyIfQueueTooLong>false</SendBusyIfQueueTooLong>
<SendBusyIfWaitTooLong>false</SendBusyIfWaitTooLong>
<TimeInOverflow>-1</TimeInOverflow>
<TimeWithDirectDDI>20000</TimeWithDirectDDI>
<TimeWithPrimaryTeams>-1</TimeWithPrimaryTeams>
<TimeWithSecondaryTeams>20000</TimeWithSecondaryTeams>
<UseDirectDDI>false</UseDirectDDI>
<UsePAM>false</UsePAM>
<UseSecondaryTeams>false</UseSecondaryTeams>
<WrapTime>40000</WrapTime>
</SimpleStrategy>'
I then created the following SQL Statement to try and extract the Teams
;WITH XMLNAMESPACES ('http://www.w3.org/2001/XMLSchema-instance' as i, 'http://schemas.microsoft.com/2003/10/Serialization/Arrays' as d2p1,
DEFAULT 'http://schemas.datacontract.org/2004/07/Synthesys.Switch.ACD')
SELECT #xml,
#xml.value('(/SimpleStrategy/Name)[1]', 'varchar(255)'),
#xml.value('(/SimpleStrategy/PrimaryTeams)[1]', 'int') as PrimaryTeams,
#xml.value('(/SimpleStrategy/SecondaryTeams)[1]', 'int') as SecondaryTeams,
#xml.value('(/SimpleStrategy/OverflowTeams)[1]', 'int') as OverflowTeams
But all I get is the TeamID's concatenated together.
,PrimaryTeams,SecondaryTeams,OverflowTeams
Default,31,0,0
Any ideas?
Thanks
Matt
Your XML shows two team IDs in <PrimaryTeams>, while both other team nodes are empty... You did not tell us anything about the expected counts in there. However, the following approach will return a kind of entity-value-pairs with all IDs for all Teams. Hope this is what you need:
;WITH XMLNAMESPACES ('http://www.w3.org/2001/XMLSchema-instance' as i, 'http://schemas.microsoft.com/2003/10/Serialization/Arrays' as d2p1,
DEFAULT 'http://schemas.datacontract.org/2004/07/Synthesys.Switch.ACD')
SELECT 'Name' AS Caption
,1 AS RowInx
,#xml.value('(/SimpleStrategy/Name)[1]', 'varchar(255)') AS Content
UNION ALL
SELECT 'Primary Team'
,ROW_NUMBER() OVER(ORDER BY (SELECT NULL))
,t.value('.','varchar(255)')
FROM #xml.nodes('/SimpleStrategy/PrimaryTeams/d2p1:int') A(t)
UNION ALL
SELECT 'Secondary Team'
,ROW_NUMBER() OVER(ORDER BY (SELECT NULL))
,t.value('.','varchar(255)')
FROM #xml.nodes('/SimpleStrategy/SecondaryTeams/d2p1:int') A(t)
UNION ALL
SELECT 'Overflow-Team'
,ROW_NUMBER() OVER(ORDER BY (SELECT NULL))
,t.value('.','varchar(255)')
FROM #xml.nodes('/SimpleStrategy/OverflowTeams/d2p1:int') A(t);

How do I extract data from an XMLTYPE field by attribute?

Forgive me for being a total beginner.
I am looking at a column named FORM_XML that is described as data type XMLTYPE.
The contents of one field is:
<Form FormID="0" Name="Preventive Care(F)">
<FormObject Name="prevcare01" Type="DateTime" Label="Physical Exam" EditValue="04/05/2007" />
<FormObject Name="prevcare02" Type="DateTime" Label="Lipid Profile" EditValue="NoEditValue" />
<FormObject Name="prevcare03" Type="DateTime" Label="Health Care Proxy review" EditValue="NoEditValue" />
<FormObject Name="prevcarecomm" Type="Text" Label="Comments" EditValue="NoEditValue" />
</Form>
The goal is to extract the EditValue date where Label="Physical exam". In this example, the date 04/05/2007 is what I want to extract. Is there a magic query that can accomplish this?
Existing questions haven't helped because their XML data is structured differently. Is my XML data structured wrong because it doesn't contain namespaces, and specific labels?
FOLLOW-UP QUESTION:
I ran
SELECT Extract(form_xml, '/Form/FormObject/#EditValue') FROM patient_form;
And got the EditValue for all FormObjects concatenated together. Is it possible to filter out just the EditValue where Label="Physical exam"?
You can use XMLTABLE to convert XML to rows and columns and then apply your filter.
Query:
SQL> with x(y) as (
select xmltype('<Form FormID="0" Name="Preventive Care(F)">
<FormObject Name="prevcare01" Type="DateTime" Label="Physical Exam" EditValue="04/05/2007" />
<FormObject Name="prevcare02" Type="DateTime" Label="Lipid Profile" EditValue="NoEditValue" />
<FormObject Name="prevcare03" Type="DateTime" Label="Health Care Proxy review" EditValue="NoEditValue" />
<FormObject Name="prevcarecomm" Type="Text" Label="Comments" EditValue="NoEditValue" />
</Form>') from dual
)
select z.*
from x cross join
xmltable('Form/FormObject' passing x.y
columns label_ varchar2(30) path '#Label',
editvalue_ varchar2(30) path '#EditValue'
) z
where z.label_ = 'Physical Exam';
Result:
LABEL_ EDITVALUE_
------------------------------ ------------------------------
Physical Exam 04/05/2007
Or use XQuery to filter it before converting to rows and columns.
Query:
SQL> with x(y) as (
select xmltype('<Form FormID="0" Name="Preventive Care(F)">
<FormObject Name="prevcare01" Type="DateTime" Label="Physical Exam" EditValue="04/05/2007" />
<FormObject Name="prevcare02" Type="DateTime" Label="Lipid Profile" EditValue="NoEditValue" />
<FormObject Name="prevcare03" Type="DateTime" Label="Health Care Proxy review" EditValue="NoEditValue" />
<FormObject Name="prevcarecomm" Type="Text" Label="Comments" EditValue="NoEditValue" />
</Form>') from dual
)
select z.*
from x cross join
xmltable('for $i in /Form/FormObject
where $i/#Label = "Physical Exam"
return $i' passing x.y
columns label_ varchar2(30) path '#Label',
editvalue_ varchar2(30) path '#EditValue'
) z;
Result:
LABEL_ EDITVALUE_
------------------------------ ------------------------------
Physical Exam 04/05/2007
Namespaces are usually what makes life complicated, no namespace should be simpler.
/Form/FormObject/#EditValue

Parse out XML Value in SQL Server

I have the following XML contained in a column XML_TRANSACTION in a table TRANSACTION in SQL Server. I am trying to parse out the information inside the From and To tags into separate columns:
<Transaction Id="1234" Timestamp="2012-04-28T05:02:20" Version="TransactionVersion2" SenderId="abcd" SenderLocId="vxyz">
<Instance Name="Home" />
<Messages>
<Message Id="0" Timestamp="2014-04-28T01:00:46">
<MessageRequest Name="Movement" Xsd="Movement.xsd" Version="5">
<Body>
<Parts>
<Part PartNumber="11111" Qty="1" PersonUniqueId="A1B2C3" />
</Parts>
<Order Number="13579" Uid="01" />
<Ship Number="1ZW23" Type="Out" />
<From VendorId="XY1X2" VendorLocId="XY1X2" VendorName="Vendor_Extra" VendorStockRoom="OPEN" CountryCode="US" />
<To VendorId="XY1X2" VendorLocId="XY1X2" VendorName="Vendor_Extra" VendorStockRoom="CLOSED" CountryCode="US" />
</Body>
</MessageRequest>
</Message>
</Messages>
</Transaction>
Desired results:
From_VendorID || From_VendorLocID || From_VendorName || To_VendorID || To_VendorLocID
--------------++------------------++--------------------------------------------------
XY1X2 || XY1X2 || Vendor_Extra || XY1X2 || XY1X2
etc.
I have made several attempts, but have been unsuccessful. Any assistance would be greatly appreciated!
This should get you started:
SELECT
t.[XML_TRANSACTION].value('(//From/#VendorId)[1]','varchar(20)') as From_VendorID
,t.[XML_TRANSACTION].value('(//From/#VendorLocId)[1]','varchar(20)') as From_VendorLocID
,t.[XML_TRANSACTION].value('(//To/#VendorLocId)[1]','varchar(20)') as To_VendorLocID
,t.[XML_TRANSACTION].value('(//To/#VendorLocId)[1]','varchar(20)') as To_VendorLocID
FROM [CD].[TEST] AS t

update xml attribute in xml returns error SQL

Im trying to update an attribute of an xml in SQL.
My XML is stored on a variable #tmpRespXML:
<Responses>
<x id="3" name="Good" val="0" seq="0" createsr="0" />
<x id="4" name="Fair" val="0" seq="0" createsr="0" />
<x id="5" name="Needs Repair" val="1" seq="0" createsr="0" />
<x id="6" name="Not Inspected" val="1" seq="0" createsr="0" />
<x id="7" name="N/A" val="1" seq="0" createsr="0" />
</Responses>
So what I did is to put the xml in a temp table.
DECLARE #tmpRespTBL TABLE(Responses XML)
INSERT #tmpRespTBL VALUES(#tmpRespXML)
and then update the table. I'm trying to set the attribute #createsr to 1 where my attribute #id is equal to #items
UPDATE #tmpRespTBL
SET Responses.modify('replace value of(/Responses/x[#id=("'+#items+'")]/#createsr)[1] with "1"')
This returns the ff error:
Msg 8172, Level 16, State 1, Line 30 The argument 1 of the xml data
type method "modify" must be a string literal.
What am I missing here?
Try with
SET Responses.modify('replace value of(/Responses/x[#id=("''+#items+''")]/#createsr)[1] with "1"')
That should fix your issue. What I did here is escape the '