How to import part of xml to mysql table?

泄露秘密 提交于 2019-12-13 07:18:56

问题


I'd like to import some of the items in an large xml file to mysql table. Lets say the xml contains thousands of items like:

<CD>
<TITLE>Empire Burlesque</TITLE>
<ARTIST>Bob Dylan</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>Columbia</COMPANY>
<PRICE>10.90</PRICE>
<YEAR>1985</YEAR>
</CD>

But I need only 'TITLE' and 'YEAR' of each CD to be imported to mysql's cd table.

I know that there is a 'LOAD XML' mysql 5.+ to get data from xml to mysql, but apparently it maps the whole xml, which is not what I need. So I appreciate your help.


回答1:


Use SimpleXML to load the XML and then loop through the values. My example uses simplexml_load_string() you can just as easily use simple_load_file()

Example

$string = <<<XML
<?xml version='1.0'?> 
<CDS>
<CD>
<TITLE>Empire Burlesque</TITLE>
<ARTIST>Bob Dylan</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>Columbia</COMPANY>
<PRICE>10.90</PRICE>
<YEAR>1985</YEAR>
</CD>
<CD>
<TITLE>Empire Burlesque2</TITLE>
<ARTIST>Bob Dylan</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>Columbia</COMPANY>
<PRICE>10.90</PRICE>
<YEAR>1986</YEAR>
</CD>
</CDS>
XML;

$xml = simplexml_load_string($string);

foreach ($xml as $cd) 
{
    // Your mysql functions for inserting goes here
    echo $cd->TITLE . "<br>";
    echo $cd->YEAR . "<br>";
}

See it in action

Hopefully that gives you a point in the right direction.




回答2:


So you can have this approach to get the job done:

  • Convert your big XML file with all elements into a smaller XML file with only needed element
    using XSLT transformation
  • Than using XML parsers like SAXON, DOM or other parse the new small XML file
  • Use some programming language that will do the parsing and database dumping part for you.
    For example if you plan to use java you can use concept called as JAXB to unmarshall your XML to java objects and than populate them into database.

If you can share more information about your original XML and what elements you want from them I can post solution in JAVA for you.

Hope this will help you.




回答3:


Thanks abase omment, I just figured out that the easiest way to import necessary fields from xml to mysql table is to use the built in Load XML feature of mysql, like:

 LOAD XML LOCAL INFILE '/path/to/file.xml' INTO TABLE  cds ROWS IDENTIFIED BY '<CD>';

Where you previously created cds table by the columns that you need from file.xml.

Just notice that in mysql 5.5+ you need to add '--local-infile ' flag when you enter the mysql command line, otherwise you get an ERROR 1148.



来源:https://stackoverflow.com/questions/15031249/how-to-import-part-of-xml-to-mysql-table

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