1

With the conditions:

  1. I cannot use any XML parser tool as I don't have permission , read only

  2. My xmllint version does not support xpath, and I cannot update it , read only

  3. I dont have xmlstarlet and cannot install it

My options are limited to almost String processing.

An input parameter will be provided by the user and it will be the name of the block.

So,

let's assume

NAME=${USER_INPUT} 

and we will use $NAME as the parameter to search the xml block that will be searched.

How can I convert a generic xml block like this in an xml file like this:

<block> <name>Bob</name> <address>USA</address> <email>[email protected]</email> <phone>1234567</phone> </block> <block> <name>Peter</name> <food>France</address> <cell>[email protected]</cell> <drinks>Coke</drinks> <car>Honda</car> <bike>Mountain bike</bike> </block> 

So the thing that I want to achieve here is to get the xml block that satisfies my search ,

for example NAME=Bob ;

The output of the script should be in properties file format

name=Bob address=USA [email protected] phone=1234567 

A thing to consider here is that the xml format per block are different. The nodes are not the same for every xml block.

2
  • Is the input file always as simple as you show? Is there always an empty line between each <block>? Can you use perl or awk?
    – terdon
    CommentedJun 24, 2015 at 17:12
  • some has empty line , some has none. yes I can use perl or awkCommentedJun 24, 2015 at 17:52

1 Answer 1

2

Perl has a nifty "paragraph mode" (-00) where records ("lines") are separated by a blank line instead of a single \n character. Using this, you can very easily extract the relevant records. So, first make sure that there is a blank line before each <block>, and then use paragraph mode to find what you're searching for:

$ sed 's/<block>/\n<block>/' file | perl -00ne 'if(/<name>\s*bob\s*<\/name>/i){print}' <block> <name>Bob</name> <address>USA</address> <email>[email protected]</email> <phone>1234567</phone> </block> 

Now, wrap this in a shell script (using bash here):

#!/bin/ksh ## Read the search strings tag="$1" value="$2" target="file.xml" ## change this to whatever your xml file is called ## Search sed 's/<.\?block>/\n/' "$target" | perl -00ne "if(/<$tag>\s*$value\s*<\/$tag>/i){ ## May as well do the formatting in Perl as well s# *<([^/]+?)>#\1=#g; s/<\/.+?>//g; print }" 

Then, run the script giving the tag name and desired value as input:

$ a.sh "name" "bob" name=Bob address=USA [email protected] phone=1234567 
0

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.