从xmltype oracle中删除Empty标记

时间:2017-11-14 18:26:32

标签: sql xml oracle

我想尝试从xmltype中删除空标记。我从oracle类型生成了以下xml。在集合中,几个元素没有值,因此我使用空标记生成。

任何人都可以帮助我:

实际输出:

<MESSAGE>
<LOCATIONS>
  <LOCATION_ID>9999</LOCATION_ID>
  <LOC_TYPE>S</LOC_TYPE>
  <NAME>Test Location</NAME> 
  <PHONE_NUM>08 </PHONE_NUM>
   <LAST_MODIFIED_BY/>
   <LAST_MODIFIED_DATE/>
   <POS_CODE/>
</LOCATIONS>
</MESSAGE>

预期产出:

<MESSAGE>
<LOCATIONS>
  <LOCATION_ID>9999</LOCATION_ID>
  <LOC_TYPE>S</LOC_TYPE>
  <NAME>Test Location</NAME> 
  <PHONE_NUM>08 </PHONE_NUM>
</LOCATIONS>
</MESSAGE>

2 个答案:

答案 0 :(得分:2)

使用DELETEXML并查找XPath //*[not(text())][not(*)]以查找不包含文字且没有子项的元素:

SQL Fiddle

Oracle 11g R2架构设置

CREATE TABLE table_name ( xml ) AS
SELECT XMLTYPE( '<MESSAGE>
<LOCATIONS>
  <LOCATION_ID>9999</LOCATION_ID>
  <LOC_TYPE>S</LOC_TYPE>
  <NAME>Test Location</NAME> 
  <PHONE_NUM>08 </PHONE_NUM>
   <LAST_MODIFIED_BY/>
   <LAST_MODIFIED_DATE/>
   <POS_CODE/>
</LOCATIONS>
</MESSAGE>' ) FROM DUAL;

查询1

SELECT DELETEXML(
         xml,
         '//*[not(text())][not(*)]'
       ).getStringVal()
FROM   table_name

<强> Results

|                                                                                            DELETEXML(XML,'//*[NOT(TEXT())][NOT(*)]').GETSTRINGVAL() |
|-----------------------------------------------------------------------------------------------------------------------------------------------------|
| <MESSAGE><LOCATIONS><LOCATION_ID>9999</LOCATION_ID><LOC_TYPE>S</LOC_TYPE><NAME>Test Location</NAME><PHONE_NUM>08 </PHONE_NUM></LOCATIONS></MESSAGE> |

答案 1 :(得分:0)

    SELECT
        deletexml(xml_data, '//*[not(text())][not(*)]').getstringval()
    FROM
        (
            SELECT
                xmltype('<MESSAGE>
    <LOCATIONS>
      <LOCATION_ID>9999</LOCATION_ID>
      <LOC_TYPE>S</LOC_TYPE>
      <NAME>Test Location</NAME> 
      <PHONE_NUM>08 </PHONE_NUM>
       <LAST_MODIFIED_BY/>
       <LAST_MODIFIED_DATE/>
       <POS_CODE/>
    </LOCATIONS>
    </MESSAGE>'
                ) xml_data
            FROM
                dual
        )

这很好,谢谢