如何使用PL SQL函数从xmltype数据生成xml报告

时间:2016-02-19 04:31:19

标签: xml oracle plsql

我是pl / sql和xml.I中的新手。将以下xml数据存储在oracle表中。

<?xml version="1.0"?>
<Company>
    <Employee>
        <Programmer>
            <Salary>2000</Salary>
            <Facilities>
                <Car>bmw</Car>
                <Apartment>1</Apartment>
                <Bonus>2000</Bonus>
            </Facilities>
        </Programmer>
        <Manager>
            <Salary>1500</Salary>
            <Facilities>
                <Car>ford</Car>
                <Room>1</Room>
                <Bonus>1500</Bonus>
            </Facilities>
        </Manager>
    </Employee>
</Company>

我想写这样的函数:

getEmployee('Programmer');

返回以下结果:

<Programmer>
    <Salary>2000</Salary>
     <Facilities>
         <Car>bmw</Car>
         <Apartment>1</Apartment>
         <Bonus>2000</Bonus>
    </Facilities>
    </Programmer>

那么如何编写这样的函数。请帮忙。谢谢

1 个答案:

答案 0 :(得分:1)

您不需要PL / SQL函数来返回XML文档的各个部分。您可以使用XQuery功能直接SELECT部分XML文档。这也意味着如果您想隐藏查询本身,仍然可以围绕XQuery SELECT创建PL / SQL函数:

CREATE TABLE XMLTEST (xmlcol XMLTYPE);

INSERT INTO XMLTEST (xmlcol) VALUES ('<?xml version="1.0"?>
<Company>
    <Employee>
        <Programmer>
            <Salary>2000</Salary>
            <Facilities>
                <Car>bmw</Car>
                <Apartment>1</Apartment>
                <Bonus>2000</Bonus>
            </Facilities>
        </Programmer>
        <Manager>
            <Salary>1500</Salary>
            <Facilities>
                <Car>ford</Car>
                <Room>1</Room>
                <Bonus>1500</Bonus>
            </Facilities>
        </Manager>
    </Employee>
</Company>');

COMMIT;

SELECT XMLQUERY('//Programmer' PASSING xmlcol RETURNING CONTENT)
  FROM XMLTEST;

<Programmer>
  <Salary>2000</Salary>
  <Facilities>
    <Car>bmw</Car>
    <Apartment>1</Apartment>
    <Bonus>2000</Bonus>
  </Facilities>
</Programmer>

注意:以上查询将提取任何名为&#34; Programmer&#34;由于在QXuery表达式&#34; // Programmer&#34;中使用了双斜杠。如果层次结构是固定的,或者如果您只想检索下面列出的任何程序员,则必须相应地在XQuery中指定该路径:

SELECT XMLQUERY('/Company/Employee/Programmer'
                PASSING xmlcol RETURNING CONTENT)
  FROM XMLTEST;

<Programmer>
  <Salary>2000</Salary>
  <Facilities>
    <Car>bmw</Car>
    <Apartment>1</Apartment>
    <Bonus>2000</Bonus>
  </Facilities>
</Programmer>