1

Newbie in shell scripting here. How do i read, for example, every name from following xml code and put all names in columns?

<rates>
   <currency>
      <name>Australian dollar</name>
      <rate>2.34</rate>
      <amount>1</amount>
   </currency>
   <currency>
      <name>GB Pounds</name>
      <rate>4.12</rate>
      <amount>1</amount>
   </currency>
   <currency>
      <name>Euro</name>
      <rate>3.45</rate>
      <amount>1</amount>
   </currency>
   <currency>
      <name>USA dollar</name>
      <rate>2.55</rate>
      <amount>1</amount>
   </currency>
   <currency>
      <name>Russian ruble</name>
      <rate>7.72</rate>
     <amount>100</amount>
   </currency>
1

2 Answers 2

1

As someone noted, 'sed' is a fine way to extract a given element from an XML file -- so long as your actual XML is as simple as the example OP gave. But beware of cases like:

  • Elements that aren't complete and alone on one line
  • Elements that can nest, like HTML lists or divs or spans....
  • Data that looks like tags but isn't -- because it's escaped, for example being inside CDATA marked sections, processing instructions, or comments.

You can sometimes handle such cases by re-line-breaking messy data first, say, so the start-tag you want to match is always at the start of a line.

If you want to get multiple elements, cover more general cases, etc., it will take a little more work. One of many ways is to convert to something trivial like CSV (I have Perl scripts out there called 'xml2tab' and 'tab2xml' that I use for this all the time).

0

you can use sed, if you just want to extract specific tag value from xml file.

 sed  -n 's/.*<name>\(.*\)<\/name>/\1/p' test.txt

 #extract and print comma separated list
 sed  -n 's/.*<name>\(.*\)<\/name>/\1/p' t1.txt | tr '\n' ','

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