【问题标题】:Python not able to save some CLOB xml into xml filePython 无法将一些 CLOB xml 保存到 xml 文件中
【发布时间】:2020-02-15 18:52:22
【问题描述】:

我在我的 oracle 数据库中将此 xml 保存为 CLOB:

<?xml version="1.0" encoding="UTF-8"?>
<DCResponse>
...
</DCResponse>

使用这个 python 代码,我可以将内容保存到 xml 文件中:

sql = "select extract(xmltype.createxml(xml), '//DCResponse').getStringVal() from table t where id = 2"
for row in cursor.execute(sql):
    print(row[0])
with open("output.xml", "w") as f:
    f.write(row[0])

用这个xml代替

<?xml version="1.0" encoding="ISO-8859-1"?>
<PIPEDocument xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:XML-PIPE 
PIPEDocument.xsd" ReferenceNumber="567862650" CreationDate="20200115155255" Version="1.0"  
xmlns="urn:XML-PIPE">
...
</PIPEDocument>

我无法使用 python 提取内容。 Write() 参数必须是 str,而不是 None .....是 Python 控制台运行此代码的结果:

sql = "select extract(xmltype.createxml(xml), '//PIPEDocument').getStringVal() from table t where id 
= 7"
for row in cursor.execute(sql):
    print(row[0])
with open("output.xml", "w") as f:
    f.write(row[0])

在我的 oracle 客户端中,python 中使用的以下 sql 查询的输出为空:

select extract(xmltype.createxml(xml), '//PIPEDocument').getStringVal() from table t where id = 7;

当 xml 内容存在于我的数据库中时:

select xml from table where id =7

不确定是什么问题,可能是选择查询中的关键字“//PIPEDocument”或两个 XML 文件之间的编码不同,但不知道如何解决。

请帮忙 最好的祝福 詹卡洛

【问题讨论】:

    标签: python xml oracle


    【解决方案1】:

    问题是在您的第二个 XML 文档中有名称空间。元素 &lt;PIPEDocument&gt; 位于命名空间 xmlns="urn:XML-PIPE" 中,而您的 XPath 表达式 //PIPEDocument' 仅匹配“默认”命名空间中的元素 &lt;PIPEDocument&gt;

    如果您想使用带有extract 函数的命名空间,您必须添加:

    • 前缀到命名空间 URI 的命名空间映射,使用 extract 的可选第三个参数。第三个参数是一个字符串,其格式与 XML 文档中的 xmlns:* 属性相同。你不能以这种方式映射默认命名空间,所以xmlns="urn:XML-PIPE" 在这里不起作用。相反,请使用前缀,例如 p,或者可能是 pipe

    • extract的第二个参数中添加XPath表达式的前缀。

    我对您的代码进行了这些更改,选择使用命名空间前缀p。我还将整个 SQL 字符串用三引号括起来,以避免我不得不转义其中的引号。这给了我以下内容,它返回了所需的 XML 输出:

    sql = """select extract(xmltype.createxml(xml), '//p:PIPEDocument', 'xmlns:p="urn:XML-PIPE"').getStringVal() from table t where id = 7"""
    for row in cursor.execute(sql):
        print(row[0])
    

    【讨论】:

      【解决方案2】:

      为了查询性能,您可能希望将 LOB 作为字符串获取,请参阅doc

      作为一般参考,如果数据库类型是 XMLType,cx_Oracle's recommendation 将使用xmltype.getclobval() 以避免有限的 XML 长度。

      【讨论】:

        猜你喜欢
        • 2011-10-10
        • 1970-01-01
        • 2016-08-09
        • 1970-01-01
        • 2014-11-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多