Problems with MySQL LOAD XML INFILE

落花浮王杯 提交于 2019-12-04 10:50:48

I couldn't find a way to do this using LOAD XML INFILE while preserving the CDATA contents. However, the following works and uses good old LOAD DATA INFILE along with ExtractValue() to accomplish the same thing:

If we have your example file and this table:

CREATE TABLE `yahootable` (
  `id` int(11) NOT NULL PRIMARY KEY,
  `various` text,
  `message` text
) ENGINE=InnoDB DEFAULT CHARSET=utf8
;

then running this statement will import the contents of the file into the table:

LOAD DATA INFILE 
    '/tmp/yahootable.xml'
INTO TABLE 
    yahootable
CHARACTER SET 'utf8'
LINES STARTING BY '<row>' TERMINATED BY '</row>'
(@tmp)
SET
  id      = ExtractValue(@tmp, '//id'),
  various = ExtractValue(@tmp, '//various'),
  message = ExtractValue(@tmp, '//message')
;

This works by telling LOAD DATA INFILE that each <row>...</row> is a logical 'line', which it stores in the local variable @tmp. We then pass this to the ExtractValue function as an XML fragment and select the values from it that we want using the appropriate XPath expressions.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!