为什么这个 "extractvalue" returns null

Why this "extractvalue" returns null

我需要直接从 xml 文件中提取值,精确到一个字段,但我总是得到 NULL 值。

我可以毫无问题地将文件导入 table。该文件位于 c:\xampp\mysql\data\test_folder\test_file.xml.

我是这样导入的:

LOAD XML INFILE 'test_file.xml'
INTO TABLE tbl_tutorials
CHARACTER SET utf8
ROWS IDENTIFIED BY '<row>'
;

而且我已经用这种方式创建了 table

    CREATE TABLE IF NOT EXISTS tbl_tutorials(
    item_id INT(11) NOT NULL,
    title VARCHAR(100) NOT NULL,
    link VARCHAR(120) NOT NULL,
    description VARCHAR(400) NOT NULL,
    keywords VARCHAR (50) NOT NULL
) ;

我的test_file.xml是这个

<?xml version="1.0" encoding="UTF-8"?>
<tbl_tutorials>
<row>
    <item_id>1</item_id>
    <title>test title 1</title>
    <link>test link 1</link>
    <description>test description 1</description>
    <keywords>test keyword  1</keywords>
</row>
<row>
    <item_id>2</item_id>
    <title>test title 2</title>
    <link>test link 2</link>
    <description>test description 2</description>
    <keywords>test keyword 2</keywords>
</row>
<row>
    <item_id>3</item_id>
    <title>test title 3</title>
    <link>test link 3</link>
    <description>test description 3</description>
    <keywords>test keyword 3</keywords>
</row>

</tbl_tutorials>

我想做的是创建一个包含所有 xml 代码的 "var"(不知道这是否是确切的术语),然后从该变量中提取所需的值。

这边...

SET @xmlFile = load_file('c:\xampp\mysql\data\test_folder\test_file.xml ');
SELECT extractvalue(@xmlFile , '/tbl_tutorials/row/keywords') keywords;

我得到的是

------------
| keywords |
------------
|NULL      |
------------

而我需要的是

----------------
| keywords     |
----------------
|test keyword 1|
----------------

我认为我必须准确指定需要哪个子元素,但我不知道为什么总是 returns 我为 null。

我正在使用 mySql workbench 和 Xampp

谢谢大家

编辑

我刚刚在文件路径中添加了反斜杠“\”,现在提取值 returns "blob",这样

SET @xmlFile = load_file('c:\xampp\mysql\data\test_folder\test_file.xml ');



------------
| keywords |
------------
|BLOB      |
------------

您的 xml 文件无效,缺少结尾 </tbl_tutorials>,因此您得到 null(无论您尝试提取什么)。

如果修复它,您的查询将 return 每个关键字,请参阅 ExtractValue 的文档:

If multiple matches are found, the content of the first child text node of each matching element is returned (in the order matched) as a single, space-delimited string.

要获取第一个 "row" 标签的关键字,您可以使用

SELECT ExtractValue(@xmlFile , '/tbl_tutorials/row[1]/keywords') keywords

请注意,"row"-标签是编号的,而不是关键字。如果您使用

SELECT ExtractValue(@xmlFile , '/tbl_tutorials/row/keywords[1]') keywords

你得到每一行的第一个关键字,在你的例子中是每个关键字;你可以使用它,例如每行有几个关键字,那么这将为您提供第一个(每行的)。

您还可以通过属性指定行,例如一个 item_id:

SELECT ExtractValue(@xmlFile , '/tbl_tutorials/row[item_id="1"]/keywords') keywords

要获取关键字标签的总数(由您的原始查询return编辑),您可以使用

SELECT ExtractValue(@xmlFile , 'count(/tbl_tutorials/row/keywords)') cnt 

我在这里找到了 BLOB 问题和一般问题的解决方案

MySQL Workbench shows results as BLOB

谢谢大家