How to get a field from an XML?

We have an input XML of the following form

<item>
<account>1234</account>
<id>345</id>
</item>

How do we get the value of <account> tag (1234) using UNIX ?

Try this,

awk '/<account>/' inputfile

Thanks Pravin. But we still get the entire xml.
Our input xml looks like:

 <doc>
     <str name="account_id">1111</str> 

    <str name="prd_id">DHEP155EK</str>  

   </doc>


  - <doc>
     <str name="account_id">6666</str> 

    <str name="prd_id">394531662</str>  

   </doc>


  - <doc>
     <str name="account_id">6666</str> 

    <str name="prd_id">394805955</str>  

   </doc>

here we want to get the account_id|prd_id to another text file, output.txt like:

1111|DHEP155EK
6666|394531662
6666|394805955

Can you help?

Try...

awk -F '[<>]' '$2~/account_id|prd_id/ {print $3}' file1 | paste -d '|' - -

awk '{print $0}' input.xml gives the whole text in a single line. Hence i guess none of the above codes are working!:wall:

awk -F "[><]" '/"account_id"/{printf $3} /"prd_id"/ {print "|" $3}' infile

First of all, what you are showing us in not an XML document. It is a text document using XML-like tags. A valid XML document (example.xml) has a single root, i.e.

<docs>
  <doc>
     <str name="account_id">1111</str>
     <str name="prd_id">DHEP155EK</str>
  </doc>
  <doc>
     <str name="account_id">6666</str>
     <str name="prd_id">394531662</str>
  </doc>
</docs>

If you have a valid document, you can use an XSL stylesheet to quickly contain the output you want.

For example, here is a stylesheet (example.xsl):

<xsl:stylesheet version="1.0"
   xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

   <xsl:output method="text"/>

   <xsl:template match="/">
      <xsl:apply-templates select="docs"/>
   </xsl:template>

   <xsl:template match="docs">
      <xsl:apply-templates select="doc"/>
   </xsl:template>

   <xsl:template match="doc">
      <xsl:value-of select="./str[@name='account_id']" />|<xsl:value-of select="./str[@name='prd_id']" />
<xsl:text>
</xsl:text>
   </xsl:template>

</xsl:stylesheet>

which when used with a XSLT engine such as xsltproc produces the output you want:

$ xsltproc example.xsl example.xml
1111|DHEP155EK
6666|394531662