Question

I am trying to insert some XML into a MySQL table but am having some trouble because I only want to insert certain attributes and not all the attributes in the XML file.

Here is subset of the XML: <rosters> <team id="1" team_name="Ravens"> <players> <player id="28" jersey_number="34" first_name="Joe" last_name="Flacco"/> <player id="4" jersey_number="43" first_name="Ray" last_name="Lewis"/> </players> </team> <team id="2" team_name="Broncos"> <players> <player id="9" jersey_number="5" first_name="Peyton" last_name="Manning"/> </players> </team> </rosters>

I want to loop through each team and insert the players on the team with certain attributes.

These would be the columns in the MySQL table: player_id(primary key and autoincrement), first_name, last_name, and the player's respective team.

This would be the desired table after inserting the attributes:

player_id, first_name, last_name,   team
        1,        Joe,    Flacco,  Ravens
        2,        Ray,     Lewis,  Ravens
        3,     Peyton,   Manning, Broncos

I am new to XML and most of the answers I have found usually insert all elements into a single table. It would be much appreciated if someone could help me with my specific question or direct me to a resource.

Was it helpful?

Solution

LOAD XML is what you are looking for.

Similarly to the LOAD DATA command (just replace DATA with XML in the example provided):

You can also discard an input value by assigning it to a user variable and not assigning the variable to a table column:

LOAD DATA INFILE 'file.txt'
INTO TABLE t1
(column1, @dummy, column2, @dummy, column3);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top