1

I have to read specific tag attributes from an XML-file and return them to a Template-Document.
I've finished reading the file itself, now how can I read one tag only and parse its attributes?

<?xml version="1.0" encoding="UTF-8"?>
<instances
name="instance-name"
port="60535"
username="bar"
password="foo"
string_var="barfoo">
some xml (up to 5k lines and 3 k elements i do not need)
</instances>

How can I read the string until I encounter the ">" for instances? And how can I put the values into variables?

Wanted output:

TPAR_PORT = 60535
TPAR_USERNAME = bar
TPAR_PASSWORD = foo
TPAR_INSTANCE = instance-name

By the way it does not matter if the values are with or without single quotes

Kevin Bowen
  • 1,625
  • 2
  • 23
  • 27
Vogel612
  • 5,620
  • 5
  • 48
  • 73
  • possible duplication: http://stackoverflow.com/questions/4680143/how-to-parse-xml-using-shellscript – xiaoyi Jan 08 '13 at 07:44
  • problem is where to start and if the lines are separate as with kate or gedit, or if its one line as in normal opening. also i only need the attributes from the instances tag. some xml can be up to 5k lines of xml and i don't wanna select parser output... – Vogel612 Jan 08 '13 at 07:53
  • Show some code. Show your expected output. Try xmlstarlet, Nokogiri, or some some other XML parser. – Todd A. Jacobs Jan 08 '13 at 08:44

2 Answers2

1

Use a proper XML parser. You example is not a well-formed XML, though: foo and bar are not allowed in the XML declaration, which must end in ?>, not a simple >. Also, encoding should be used instead of charset.

After fixing the file, you can start using the proper tools.

<?xml version="1.0" charset="UTF-8"?>
<instances
name="instance-name"
port="60535"
username="bar"
password="foo"
string_var="barfoo">
some xml
</instances>

For example, you can use xmllint and its --shell option:

$ xmllint 1.xml --shell  <<<'cat /instances/@port'
/ > cat /instances/@port
 -------
 port="60535"
/ >

My favourite tool is xsh:

$ xsh <<<'open 1.xml ; echo /instances/@port'
60535
choroba
  • 231,213
  • 25
  • 204
  • 289
0

How about this

while read
do
  eval $REPLY 2>/dev/null
done < a.xml
Zombo
  • 1
  • 62
  • 391
  • 407