2016-11-14 95 views

回答

0

函数用于创建零XML元素,我相信它可以改进:

create function add_xml_element(
    p_name in varchar2, 
    p_value in varchar2, 
    p_namespaces in varchar2 default null, 
    p_nil_prefix in varchar2 default null, 
    p_nil_namespace in varchar2 default null) return XMLType is 

    l_result XMLType; 
begin 
    if p_value is not null then 
    l_result := XMLType('<' || p_name || ' ' || p_namespaces || '>'||p_value||'</' || p_name || '>'); 
    elsif p_nil_prefix is not null and p_nil_namespace is not null then 
    l_result := XMLType('<' || p_name || ' ' || p_namespaces || ' ' || p_nil_namespace || ' ' || p_nil_prefix || ':nil="true"/>'); 
    else 
    raise_application_error(-20001, 'Nil prefix or namespace not provided'); 
    end if; 

    return l_result; 
end; 

和PLSQL脚本来测试它:

declare 
    l_xml xmlType; 

    cursor c_build_xml(cp_value in varchar2) is 
    select 
     xmlElement("root", 
     add_xml_element(
      'node', 
      cp_value, 
      null, 
      'i', 
      'xmlns:i="default"')) 
    from 
     dual; 
begin 
    open c_build_xml('nodevalue'); 
    fetch c_build_xml 
    into l_xml; 
    close c_build_xml; 

    dbms_output.put_line(l_xml.getClobVal()); 

    open c_build_xml(null); 
    fetch c_build_xml 
    into l_xml; 
    close c_build_xml; 

    dbms_output.put_line(l_xml.getClobVal()); 
end; 
/

脚本输出如下:

<root> 
    <node>nodevalue</node> 
</root> 

<root> 
    <node xmlns:i="default" i:nil="true"/> 
</root>