I am having trouble to add tags with nsmap for lxml library - lxml

I have wrote a function to generate Google Merchant RSS Feed with lxml library
I have the following code which is shortened for single tag:
from lxml import etree
def generate_xml(self):
nsmap = {
"g": "http://base.google.com/ns/1.0",
}
page = etree.Element('rss', nsmap=nsmap)
channel = etree.SubElement(page, 'channel')
channel_title = etree.SubElement(channel, 'title')
channel_title.text = "Test RSS 2.0 data feed template products"
channel_description = etree.SubElement(channel, 'description')
channel_description.text = "test data feed template."
channel_link = etree.SubElement(channel, 'link')
channel_link.text = "https://test-abcd.com"
item = etree.SubElement(channel, "item")
item_id = etree.SubElement(item, "id", nsmap=nsmap)
item_id.text = "123456789"
return etree.tostring(page, xml_declaration=True, encoding="utf-8")
The function returns the following output:
<?xml version='1.0' encoding='utf-8'?>
<rss xmlns:g="http://base.google.com/ns/1.0">
<channel>
<title>Test RSS 2.0 data feed template products</title>
<description>test data feed template.</description>
<link>https://test-abcd.com</link>
<item>
<id>123456789</id>
</item>
</channel>
</rss>
but it should be as the following (<g:id>123456789</g:id>) :
<?xml version='1.0' encoding='utf-8'?>
<rss xmlns:g="http://base.google.com/ns/1.0">
<channel>
<title>Test RSS 2.0 data feed template products</title>
<description>test data feed template.</description>
<link>https://test-abcd.com</link>
<item>
<g:id>123456789</g:id>
</item>
</channel>
</rss>

I have found the solution which is to use etree.QName() to build the qualified name for id:
def generate_xml(self):
nsmap = {
"g": "http://base.google.com/ns/1.0",
}
page = etree.Element('rss', nsmap=nsmap)
channel = etree.SubElement(page, 'channel')
channel_title = etree.SubElement(channel, 'title')
channel_title.text = "Test RSS 2.0 data feed template products"
channel_description = etree.SubElement(channel, 'description')
channel_description.text = "test data feed template."
channel_link = etree.SubElement(channel, 'link')
channel_link.text = "https://test-abcd.com"
item = etree.SubElement(channel, "item")
item_id = etree.SubElement(item, etree.QName(nsmap.get("g"), 'id'))
item_id.text = "123456789"
return etree.tostring(page, xml_declaration=True, encoding="utf-8")

Related

Beautifoul soup: ho extract <p> content of a parent balise

in a text file, each item have the same structure so I would like to parse it with beautiful soup.
An extract:
data = """
<article id="1" title="Titre 1" sourcename="Le monde" about="Fillon|Macron">
<p type="title">Sub title1</p>
<p>xxxxxxxxxxxxxxxxxxxxxxxxx</p>
</article>
<article id="2" title="Titre 2" sourcename="La Croix" about="Le Pen|Mélanchon">
<p type="title">Sub title2</p>
<p>yyyyyyyyyyyyyyyyyyyyyyyyy</p>
</article>
"""
from bs4 import BeautifulSoup
soup = BeautifulSoup(data, 'html.parser')
for text in soup.find_all('article'):
print(text['id'])
print(list(text.findChildren()))
print(list(text.children))
I want to extract "p" balise content:
For each article, I would like to get a list of list (to convert to Df panda).
For example:
[
[1, "Sub title2", "xxxxxxxxxxxxx"],
2, "Sub title2", "yyyyyyyyyyyyy"],
]
Thanks a lot.
Théo
You're almost there.
result = [] # create a variable to store your results
for article in soup.find_all("article"):
article_id = article["id"]
title = article.select("p[type=title]")[0] # select the title tag
title_text = title.text
p = title.find_next("p").text # get the adjacent p tag
result.append([article_id, title_text, p])

DataWeave 2 - transform Java ArrayList to XML with array item tags

I have a Java payload in Mule 4.3 which contains an ArrayList:
agentList = {ArrayList}
0 = {SomeClass}
id = "0"
name = "Agent0"
1 = {SomeClass}
id = "1"
name = "Agent1"
I want to transform this to XML as:
<agentList>
<agent>
<id>0</id>
<name>Agent0</name>
</agent>
<agent>
<id>1</id>
<name>Agent1</name>
</agent>
</agentList>
If I do a DataWeave transform output application/xml --- result: payload, I get this XML:
<result>
<agentList>
<id>0</id>
<name>Agent0</name>
</agentList>
<agentList>
<id>1</id>
<name>Agent1</name>
</agentList>
</result>
How can I transform the ArrayList so that I get each item enclosed by agent tags and the entire list as agentList?
%dw 2.0
output application/xml
---
result: {
agentList: payload.*agentList map (value) -> { agent: value }
}

Karate: Match repeating element in xml

I'm trying to match a repeating element in a xml to karate schema.
XML message
* def xmlResponse =
"""
<Envelope>
<Header/>
<Body>
<Response>
<Customer>
<keys>
<primaryKey>1111111</primaryKey>
</keys>
<simplePay>false</simplePay>
</Customer>
<serviceGroupList>
<serviceGroup>
<name>XXXX</name>
<count>1</count>
<parentName>DDDDD</parentName>
<pendingCount>0</pendingCount>
<pendingHWSum>0.00</pendingHWSum>
</serviceGroup>
<serviceGroup>
<name>ZZZZZ</name>
<count>0</count>
<parentName/>
<pendingCount>3</pendingCount>
<pendingHWSum>399.00</pendingHWSum>
</serviceGroup>
</serviceGroupList>
</Response>
</Body>
</Envelope>
"""
I want to match each with following karate schema
Given def serviceGroupItem =
"""
<serviceGroup>
<name>##string</name>
<count>##string</count>
<parentName>##string</parentName>
<pendingCount>##string</pendingCount>
<pendingHWSum>##string</pendingHWSum>
</serviceGroup>
"""
This is how I tried
* xml serviceGroupListItems = get xmlResponse //serviceGroupList
* match each serviceGroupListItems == serviceGroupItem
But it doesn't work. Any idea how can I make it work
You have to match each serviceGroup.
* xml serviceGroupListItems = get xmlResponse //serviceGroupList
* match each serviceGroupListItems.serviceGroupList.serviceGroup == serviceGroupItem.serviceGroup

Calling Yahoo Weather API from VoiceXML

I'm trying to make a voice weather system with voiceXML and the Yahoo Weather API. To develop my program I'm using voxeo evolution.
To call the Weather API I'm using the data vxml tag with an srcexpr because I need a dynamic URL (the program asks the user for a city to check weather in).
Here is my code:
<?xml version="1.0" encoding="UTF-8"?>
<vxml version = "2.1">
<form id="mainMenu">
<field name="City">
<prompt>
Please, name a spanish city.
</prompt>
<grammar src="city.grammar"/>
</field>
<!-- code taken from the javascript example of the yahoo weather api -->
<script>
<![CDATA[
var callbackFunction = function(data) {
var wind = data.query.results.channel.wind;
alert(wind.chill);
};
]]>
</script>
<data srcexpr="https://query.yahooapis.com/v1/public/yql?q=select * from weather.forecast where woeid in (select woeid from geo.places where text='"+City+", spain')&callback=callbackFunction"/>
</form>
</vxml>
The program doesn't work because of the data tag to connect to the weather API, but I don't know why. Do someone know why is failing?
I finally solved my problem making a php script to connect to the yahoo api and calling it using submit tag in VoiceXML.
<?php
$City = $_REQUEST["City"];
$Day = $_REQUEST["Day"];
$BASE_URL = "http://query.yahooapis.com/v1/public/yql";
$yql_query = 'select * from weather.forecast where woeid in (select woeid from geo.places(1) where text="('.$City.', spain)") and u="c"';
$yql_query_url = $BASE_URL . "?q=" . urlencode($yql_query) . "&format=json";
$session = curl_init($yql_query_url);
curl_setopt($session, CURLOPT_RETURNTRANSFER,true);
$yahooapi = curl_exec($session);
$weather = json_decode($yahooapi,true);
$weather_resumen = $weather['query']['results']['channel']['item']['forecast'];
$weather_today = $weather_resumen[0]['day'];
// yahoo api returns an array with the weather for the next week ordered by
// day (0 -> today, 1 -> tomorrow...). Function get_day gets the index of
// the day the user said
$index_weather = get_day($weather_today, $Day);
$condition_index = $weather_resumen[$index_weather]['code'];
$weather_condition = $cond_met[intval($condition_index)];
$min_temp = $weather_resumen[$index_weather]['low'];
$max_temp = $weather_resumen[$index_weather]['high'];
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
?>
<vxml version="2.1" xml:lang="es-ES">
<form id="form_main">
<block>
<prompt>
The weather for <?php echo $Day ?> in <?php echo $City ?> is <?php echo $weather_condition ?>. The lowest temperature will be <?php echo $min_temp ?> and the highest <?php echo $max_temp ?>.
<break/>
</prompt>
</block>
</form>
</vxml>

Delete/update Configurable Product with SOAP Api v2 Magento

I am trying to delete a configurable product in my cart wiht shoppingCartProductRemove with Api SOAP v2, but the api return
Please specify the product's option (s)
this is my Soap requets:
<?xml version="1.0" encoding="UTF-8"?>
<v:Envelope xmlns:v="http://schemas.xmlsoap.org/soap/envelope/" xmlns:c="http://schemas.xmlsoap.org/soap/encoding/" xmlns:d="http://www.w3.org/2001/XMLSchema" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<v:Header />
<v:Body>
<shoppingCartProductRemove xmlns="http://dev.WEBPAGE.mx/index.php/api/v2_soap" id="o0" c:root="1">
<sessionId>e6ad1063fd8f8a5b1637ec7b2bedb0ed</sessionId>
<quoteId>1016</quoteId>
<products>
<shoppingcartproductentity>
<product_id>5730</product_id>
<sku i:null="true" />
<qty>0.0</qty>
<qtySpecified>false</qtySpecified>
<options i:type="d:anyType">
<associativeentity>
<key>92</key>
<value>410</value>
</associativeentity>
<associativeentity>
<key>138</key>
<value>406</value>
</associativeentity>
</options>
<bundle_option i:type="d:anyType">
<associativeentity>
<key>92</key>
<value>410</value>
</associativeentity>
<associativeentity>
<key>138</key>
<value>406</value>
</associativeentity>
</bundle_option>
<bundle_option_qty i:null="true" />
<links i:null="true" />
</shoppingcartproductentity>
</products>
<storeId>1</storeId>
</shoppingCartProductRemove>
</v:Body>
</v:Envelope>
The configurable product is 5730 ... this have associated a simple product (id: 5735) with the attributes:
attributeID = 92 value = color (Attribute)
valueID = 410 value = black (Attribute Options)
attributeId = 138 value = Size (Attribute)
valueId = 406 value = tall (Attribute Options)
What is wrong? . How do I can remove a configurable product?