Search code examples
xmlxmlstarlet

Struggling with xmlstarlet


I have a very simple XML file that I need to parse with xmlstarlet (I'm under Windows) :

<?xml version="1.0" encoding="utf-8"?>
<Document xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.02" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <pain.001.001.02>
    <GrpHdr>
      <MsgId>IDENTIFYER</MsgId>
      <CreDtTm>2013-01-25T11:15:02</CreDtTm>
      <NbOfTxs>6</NbOfTxs>
      <CtrlSum>6268.07</CtrlSum>
      <Grpg>MIXD</Grpg>
    </GrpHdr>
   <PmtInf>
   </PmtInf>
  </pain.001.001.02>
</Document>

Let's suppose I want to retrieve CtrlSum element ; it fails when I try

xml sel -t -m "/Document/pain.001.001.02/GrpHdr" -v CtrlSum myfile.xml

But if I delete xmlns and xmlns:xsi attributes from the file it works (but I can't do that in real life). I know I have to use -N option, but i can't figure how to do that. Any help would be very valuable.

Thanks a lot Laurent (or Lawrence, or Larry :) )


Solution

  • The xmlns attribute defines the default namespace, every element you see in the XML file that doesn't have a prefix (which happens to be all of them for the example you posted) uses the default namespace. XPath doesn't allow default namespaces so you have to assign it a prefix with -N and use that when matching:

    xml sel -N p=urn:iso:std:iso:20022:tech:xsd:pain.001.001.02 -t -v /p:Document/p:pain.001.001.02/p:GrpHdr/p:CtrlSum myfile.xml