简体   繁体   中英

XML parsing with XPath and PHP handle empty values

while parsing through a XML tree like this:

<vco:ItemDetail>
    <cac:Item>
        <cbc:Description>ROLLENKERNSATZ 20X12 MM 10,5 GR.</cbc:Description>
        <cac:SellersItemIdentification>
            <cac:ID>78392636</cac:ID>
        </cac:SellersItemIdentification>
        <cac:ManufacturersItemIdentification>
            <cac:ID>RMS100400370</cac:ID>
            <cac:IssuerParty>
               <cac:PartyName>
                   <cbc:Name></cbc:Name>
               </cac:PartyName>
            </cac:IssuerParty>
        </cac:ManufacturersItemIdentification>
    </cac:Item>
    <vco:Availability>
       <vco:Code>available</vco:Code>
    </vco:Availability>
</vco:ItemDetail>

I always get a blank space which breaks my CSV structure if cbc:Name is empty, which looks like this:

"ROLLENKERNSATZ 20X12 MM 10,5 GR.";78392636;;RMS100400370;"";available

The "available" string is in a new line so my CSV is not structered any more.

My XPath array looks like this:

$columns = array('Description' => 'string(cac:Item/cbc:Description)',
          'SellersItemIdentification' => 'string(cac:Item/cac:SellersItemIdentification/cac:ID)',
          'StandardItemIdentification' => 'string(cac:Item/cac:StandardItemIdentification/cac:ID)',
          'Availability' => 'string(vco:Availability/vco:Code)',
          'Producer' => 'string(cac:Item/cac:ManufacturersItemIdentification/cac:IssuerParty/cac:PartyName/cbc:Name');

Is there any expception or replacement I can handle with like replacing the empty node value with "no producer" or something like this?

Thank you

If the value to use as the 'default' can somehow be made to exist somewhere in your input document, the problem can be solved with a quasi-coalesce like this:

eg

<vco:ItemDetail xmlns:vco="x1" xmlns:cac="x2" xmlns:cbc="x3">
   <ValueIfNoProducer>No Producer</ValueIfNoProducer>
   <cac:Item>
      ...

Then this Xpath 1.0 will apply a default if the Name element is empty or whitespace:

(cac:Item/cac:ManufacturersItemIdentification/cac:IssuerParty
     /cac:PartyName/cbc:Name[normalize-space(.)] | ValueIfNoProducer)[1]

I think the following is possible directly in XPath 2.0, but I stand to be corrected:

(cac:Item/cac:ManufacturersItemIdentification/cac:IssuerParty
     /cac:PartyName/cbc:Name[normalize-space(.)] | 'No Producer')[1]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM