Search code examples
sqlxmloracle-databaseoracle11gxml-parsing

XML Generation and output of it Using PLSQL


Below XML which need to be generated .

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Form1>
<ContentForm>
<SectionI>
<Date>13/01/2023</Date>
</SectionI>
<SectionII>
<Type>C</Type>
<ID>1809</ID>
<RIC></RIC>
<UEN>019</UEN>
<Name>Limited</Name>
</SectionII>
</ContentForm>
</Form1>
  1. Is xmlconcat correct to combine different section or is there any other approach
  2. How to generated first xml version tag and concat it in main xml?
  3. can we put it in OUT variable of PLSQL if yes how to do it
  4. how to open Form And ContentForm tag in the query .

Oracle Query

SELECT
    xmlconcat
    (   
        XMLELEMENT
        ("SectionI",XMLELEMENT("Date",SYSDATE)
        )
    ,
        XMLELEMENT
        ("SectionII",
            XMLELEMENT("Type",'C'),
            XMLELEMENT("ID",'1809'),
            XMLELEMENT("RIC",NULL),
            XMLELEMENT("UEN",'019'),
            XMLELEMENT("Name",'Limited')
        ) 
    )
    from dual
Select 
XMLELEMENT("?xml",xmlattributes('1.0' as  "Version",'UTF-8' as  "encoding",'no' as  "standalone"))
from dual

Solution

  • It would be better to use special xml functions than string functions. You can do that using xmlroot and 2 more xmlelement:

    DBFiddle: https://dbfiddle.uk/if0oBYgF

    select
        xmlroot(
              XMLELEMENT("Form1",
                 XMLELEMENT("ContentForm",
                    XMLELEMENT("SectionI",XMLELEMENT("Date",SYSDATE))
                   ,XMLELEMENT("SectionII",
                      XMLELEMENT("Type",'C'),
                      XMLELEMENT("ID",'1809'),
                      XMLELEMENT("RIC",NULL),
                      XMLELEMENT("UEN",'019'),
                      XMLELEMENT("Name",'Limited')
                   ) 
                 )
              )
            ,VERSION '1.0'
            ,STANDALONE NO
           )
        as xdata
    from dual;
    

    Result:

    XDATA
    ------------------------------------------------
    <?xml version="1.0" standalone="no"?>
    <Form1>
      <ContentForm>
        <SectionI>
          <Date>2023-06-06</Date>
        </SectionI>
        <SectionII>
          <Type>C</Type>
          <ID>1809</ID>
          <RIC/>
          <UEN>019</UEN>
          <Name>Limited</Name>
        </SectionII>
      </ContentForm>
    </Form1>