0

I have xml file with multiple <db> elements, I need to extract attributes from each node and do some work on them.

IS it possible to load them to array, using ksh and xmllint ?

This is what I have:

xml file:

<?xml version="1.0"?> <main> <resources> <db> <table_name tableid="001" user="mike">customer</table_name> </db> <db> <table_name tableid="002" user="david">orders</table_name> </db> </resources> </main> 

script:

#!/usr/bin/ksh tbid="$(echo "cat /main/resources/db/table_name/@tableid" | xmllint --shell data.xml )" username="$(echo "cat /main/resources/db/table_name/@user" | xmllint --shell data.xml )" echo $tbid echo $username 

Output:

/ > ------- tableid="001" ------- tableid="002" / > / > ------- user="mike" ------- user="david" / > 

eventually, I want to get a kind of 2-dim array:

arr[0],[0]=001 arr[0],[1]=mike arr[1],[0]=002 arr[1],[1]=david 

Notes:
xpath is not supported in xmllint , and can't be installed.
array can be represented in any other way, I just need to be able to extract and do some work.

7
  • Why the attachment to the shell? I could see Python being very effective here...
    – cat
    CommentedDec 17, 2015 at 17:48
  • this is the requirement for that specific box ( there is even no java)
    – markiz
    CommentedDec 17, 2015 at 18:26
  • Can you assume that the files will be formatted in approximately the way you presented here (e.g. with the same line breaks), or do you have to work with arbitrary XML?CommentedDec 17, 2015 at 23:32
  • Do you have perl?, because XML::Twig is really good for this sort of job.
    – Sobrique
    CommentedDec 18, 2015 at 17:14
  • @Sobrique, i will check
    – markiz
    CommentedDec 19, 2015 at 9:18

1 Answer 1

1

I'm going to offer how I'd tackle it, because you don't have any answers yet - I'd use the excellent XML::Twig module, and perl:

#!/usr/bin/env perl use strict; use warnings; use XML::Twig; my $twig = XML::Twig -> new -> parsefile ( 'data.xml' ); foreach my $table ( $twig -> get_xpath('//table_name') ) { print $table -> att('tableid'), " => ", $table -> att('user'), "\n"; } 

This prints:

001 => mike 002 => david 

Perl has a built in data structure called a hash, that might suit your needs too (depending what you're wanting):

#!/usr/bin/env perl use strict; use warnings; use Data::Dumper; use XML::Twig; my $twig = XML::Twig -> new -> parse ( \*DATA ); my %table_for; foreach my $table ( $twig -> get_xpath('//table_name') ) { my $tableid = $table -> att('tableid'); my $user = $table -> att('user'); $table_for{$user} = $tableid; } print Dumper \%table_for; 

You can iterate keys in %table_for (there's many possibilities, but I'll need an idea of what you want to expand on them)

    You must log in to answer this question.

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.