Convert XML to CSV using xml2

What you need

  • Red Hat Linux 4, 5
  • gcc
  • libxml2
  • libxml2-devel
  • xml2

Compiling xml2

1. Extract xml2 tar ball

 tar zxvf ./xml2-0.4.tar.gz

2. Modify compiling option in “configure” file

search line between 3428-3470, replace “libxml” with “libxml-2.0”

for example:


    { (echo "$as_me:$LINENO: \$PKG_CONFIG --exists --print-errors \"libxml\"") >&5
  ($PKG_CONFIG --exists --print-errors "libxml") 2>&5
  echo "$as_me:$LINENO: \$? = $ac_status" >&5
  (exit $ac_status); }; then
  pkg_cv_XML_CFLAGS=`$PKG_CONFIG --cflags "libxml" 2>/dev/null`


    { (echo "$as_me:$LINENO: \$PKG_CONFIG --exists --print-errors \"libxml-2.0\"") >&5
  ($PKG_CONFIG --exists --print-errors "libxml-2.0") 2>&5
  echo "$as_me:$LINENO: \$? = $ac_status" >&5
  (exit $ac_status); }; then
  pkg_cv_XML_CFLAGS=`$PKG_CONFIG --cflags "libxml-2.0" 2>/dev/null`

3. Run configure


4. Modify the “Makefile”

Change the “XML_CFALGS” var to

XML_CFLAGS = -I/usr/include/libxml2 -I/usr/include/libxml2/libxml

Change the LD var to

xml2_LDADD = -lxml2
2xml_LDADD = -lxml2

5. Compile it

make; make install

Now you’re able to convert your XML

The Convertion

To convert XML to CSV, first you requires to convert the XML to FLAT format using “xml2”
Sample XML

<?xml version="1.0" encoding="utf-8" ?>
<diskio idx="0" id="A1" ro="515055927" wo="238887081" rb="32271512513" wb="14177327411" re="2014322041" we="1329225665" rq="2016127681" wq="1512438860"
 ure="2014322041950" uwe="1329225665684" urq="2016127681914" uwq="1512438860723"
 pre="2218239" pwe="2081169" pro="2218241" pwo="2295886" />

Converting to FLAT format

xml2 < sample.xml > sample.txt



Convert to CSV

Choose which record and field you need, for example, under diskio scheme, @id, @ro, @re @we fields.

2csv diskio @id @ro @re @we < sample.txt > sample.csv



That’s it

Leave a Reply