How to import XML files using mysql LOAD XML LOCAL INFILE

I have an xml file similar to this:

test.xml

<?xml version="1.0" encoding="utf-8" ?>
<plugin name="tree">
    <title>Test</title>
    <description>some description</description>
    <files>
        <file>test.tmp</file>
    </files>
    <install><![CDATA[
        global $test;
    ]]></install>
    <hooks>
        <hook name="hookname"><![CDATA[
            global $local;
        ]]></hook>
    </hooks>

    <phrases>
        <phrase key="category"><![CDATA[Show categories]]></phrase>
    </phrases>
</plugin>

and I like to import it into a MySQL table, for example "mytable"

CREATE TABLE mytable (plugin varchar(255),title varchar(255),description varchar(255), file varchar(255),install varchar(255),hook varchar(255),phrase varchar(255));

I used below command

LOAD XML LOCAL INFILE 'test.xml' 
INTO TABLE mytable(plugin,title,description,file,install,hook,phrase);

succeeds but with 0 lines!

The request was successfully implemented, 0 rows affected.

thank

+4
source share
1 answer

Include this line ROWS IDENTIFIED BY '<plugin>'. so that your request should look like

LOAD XML LOCAL INFILE "D:\\test.xml"
INTO TABLE mytable
ROWS IDENTIFIED BY '<plugin>';

It seems that the formation of your XML file is incorrect and therefore even if 1 line is inserted; all values ​​are not retrieved (remains NULL).

Change a bit below

Create table structure

CREATE TABLE mytable (
plugin_name varchar(255),
title varchar(255),
description varchar(255), 
`file` varchar(255),
`install` varchar(255),
hook varchar(255),
phrase varchar(255));

Change your xml file

<?xml version="1.0" encoding="utf-8" ?>
<plugin plugin_name="tree">
    <title>Test</title>
    <description>some description</description>
         <file>test.tmp</file>
    <install>![CDATA[
        global $test;
    ]]</install>
        <hook name="hookname">![CDATA[
            global $local;
        ]]</hook>
        <phrase key="category">![CDATA[Show categories]]</phrase>
</plugin>

Now if you use

LOAD XML LOCAL INFILE "D:\\test.xml"
INTO TABLE mytable
ROWS IDENTIFIED BY '<plugin>';

All data is fined.

enter image description here

+12

Source: https://habr.com/ru/post/1542467/


All Articles