Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

Is there a way to convert XML to SQL INSERT using the command line, here is examples:

<something>
  <somthingelse>lol</somethingelse>
</something>

would be

INSERT INTO `database` (`something`)
VALUES
(lol)

Or something like that.

share|improve this question
1  
There is no reason why a program that can do that conversion (or even connects to the database to execute the SQL) cannot be run from the commandline. It just needs to be handed the name of the XML file (unless hardcoded) as a parameter. What programming language and library do you use for XML parsing? –  Anthon Oct 25 '14 at 6:04
    
Nothing. What i am is requesting a program that will do what i asked. –  DisplayName Oct 25 '14 at 6:12
    
Will you never have more levels than that? Is your entire XML file always one level deep with the outer label being the table title? –  terdon Oct 25 '14 at 10:02

1 Answer 1

With xmllint using libxml version 20708:

Name of root node "something": xmllint --xpath "name()" file.xml

Text "lol": xmllint --xpath "//*/*/text()" file.xml


Script sql.sh:

#!/bin/bash

file="$1"
table=$(xmllint --xpath "name()" "$file")
value=$(xmllint --xpath "//*/*/text()" "$file")

cat << EOF
INSERT INTO \`${table}\`
VALUES
(${value})
EOF
$ ./sql.sh file.xml

Output:

INSERT INTO `something`
VALUES
(lol)
share|improve this answer
    
Could you explain what how this works? Especially the first xmllint command which produces not output on my system. Also, even if this does work, it will only work for one table and value, presumably, if the OP needed to ask this, their real data will be much larger. –  terdon Oct 25 '14 at 10:07
    
What if there are multiple root nodes? –  DisplayName Oct 25 '14 at 11:05
    
Only with one root it's a valid XML file. –  Cyrus Oct 25 '14 at 11:08
    
But there can be nodes inside the root node. –  DisplayName Oct 25 '14 at 15:52

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.