使用命名空间提取 XML 标记 [英] Extract XML tag with namespace
问题描述
我需要提取一个 XML 标记值,如下面的代码所示.
I need to extract a XML tag value as in the code below.
设置 serveroutput on宣布lv_xml varchar2(500);xmlstring XMLTYPE;lv_val varchar2(10);开始lv_xml :='<?xml version="1.0" encoding="UTF-8"?><TestMain xmlns="http://www.w3.org/2001/XMLSchema-instance"><testTag1>VAL 1</testTag1><testTag2>VAL 2</testTag2><testTag3>VAL 3</testTag3></TestMain>';xmlstring := XMLTYPE.CREATEXML(lv_xml);选择提取值(值(fd),'testTag2')进入 lv_valFROM TABLE(XMLSEQUENCE(xmlstring.EXTRACT('TestMain'))) f,表(XMLSEQUENCE(提取(值(f),'TestMain/testTag2'))) fd;dbms_output.put_line('Val:'||lv_val);例外当其他人然后dbms_output.put_line('错误:'||SQLCODE||' '||SQLERRM);结尾;/
当我运行它时,出现异常ORA-01403: no data found
.
When I am running it, I am getting an exception ORA-01403: no data found
.
我发现,如果我删除 XML 命名空间 xmlns="http://www.w3.org/2001/XMLSchema-instance"
,那么它就可以正常工作.但是,我将从中提取值的 XML 流将采用这种格式(即,它将包含一个命名空间).
I found that, if I remove the XML namespace xmlns="http://www.w3.org/2001/XMLSchema-instance"
, then it is working fine. But, the XML stream from which I will extract values will be in this format(that is, it will contain a namespace).
有什么办法可以在 xmlns 存在的情况下提取值?
Is there any way to be able extract value with xmlns present?
推荐答案
你在这里:
declare
lv_xml varchar2(500);
xmlstring XMLTYPE;
lv_val varchar2(10);
BEGIN
lv_xml :=
'<?xml version="1.0" encoding="UTF-8"?>
<TestMain xmlns="http://www.w3.org/2001/XMLSchema-instance">
<testTag1>VAL 1</testTag1>
<testTag2>VAL 2</testTag2>
<testTag3>VAL 3</testTag3>
</TestMain>';
xmlstring := XMLTYPE.CREATEXML(lv_xml);
SELECT EXTRACTVALUE(VALUE(fd), '.')
INTO lv_val
FROM TABLE(XMLSEQUENCE(xmlstring.EXTRACT('/TestMain', 'xmlns="http://www.w3.org/2001/XMLSchema-instance"'))) f,
TABLE(XMLSEQUENCE(EXTRACT(VALUE(f), '/TestMain/testTag2', 'xmlns="http://www.w3.org/2001/XMLSchema-instance"'))) fd
;
dbms_output.put_line('Val: '||lv_val);
EXCEPTION
WHEN OTHERS THEN
dbms_output.put_line('Error: '||SQLCODE||' '||SQLERRM);
END;
/
为了代码的可读性,你可以在 select
中将特定的内容写成
And for the code readability sake you can write the particular inside select
as
SELECT EXTRACTVALUE(xmlstring, '/TestMain/testTag2', 'xmlns="http://www.w3.org/2001/XMLSchema-instance"')
INTO lv_val
FROM dual;
甚至更具可读性(尽管功能上不是 100% 相同)
or even more readable (though functionally not 100% identical)
lv_val := xmlstring.extract('/TestMain/testTag2/text()', 'xmlns="http://www.w3.org/2001/XMLSchema-instance"').getStringVal();
这篇关于使用命名空间提取 XML 标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!