Home > Enterprise >  is it posible to find whole xml node by a certaing tag value
is it posible to find whole xml node by a certaing tag value

Time:02-19

I have the following xml node.

<offer id="SD00025386">
                <picture>https://isw.b2b-sandi.com.ua/imagecache/full/1/9/19289.jpg</picture>
                <picture>https://isw.b2b-sandi.com.ua/imagecache/full/1/9/19289/19289_1.jpg</picture>
                <name>Трап ANI Plast TA1612 горизонтальний з нержавіючою решіткою 150x150</name>
                <available>true</available>
                <oldCode>19289</oldCode>
                <model>TA1612</model>
                <purchase_price>405.158</purchase_price>
                <currency>UAH</currency>
                <retail_price>691</retail_price>
                <retail_oldprice></retail_oldprice>
                <retail_currency>UAH</retail_currency>
                <outlets>
                    <outlet id="85" name="Харків" instock="1"></outlet>
                    <outlet id="86" name="Київ" instock="3"></outlet>
                    <outlet id="87" name="Україна" instock="16"></outlet>
                </outlets>
                <vendor>Ани Пласт</vendor>
                <vendorCode>SD00025386</vendorCode>
            </offer>

And I would like to search for all nodes where a vendeor has certain attribute for example

<vendor>Qtap</vendor>

And copy to an other xml whole offer node with this vendor. I can search for this value using search, but then I must copy by hand whall node. There are around 2000 of them. Is it posible to automate this using Notepad for example or it will be a better solution to write a script for this using PHP or any other language.

CodePudding user response:

If I understand you correctly, you can do something like this, using python, lxml and xpath, and a very simplified version of your xml, with two offers:

from lxml import etree

offers = """<?xml version="1.0" encoding="UTF-8"?>
<offers>
   <offer id="SD00025386">
      <retail_currency>UAH</retail_currency>
      <vendor>Ани Пласт</vendor>
      <vendorCode>SD00025386</vendorCode>
   </offer>
   <offer id="SD11125386">
      <retail_currency>USD</retail_currency>
      <vendor>Qtap</vendor>
      <vendorCode>SD11125386</vendorCode>
   </offer>
</offers>
"""

doc = etree.XML(offers.encode())
target = doc.xpath('//offer[./vendor/text()="Qtap"]')[0]
print(etree.tostring(target).decode())

Output:

<offer id="SD11125386">
      <retail_currency>USD</retail_currency>
      <vendor>Qtap</vendor>
      <vendorCode>SD11125386</vendorCode>
   </offer>
  • Related