logo
down
shadow

Element Tree - Seaching for specific element value without looping


Element Tree - Seaching for specific element value without looping

Content Index :

Element Tree - Seaching for specific element value without looping
Tag : python , By : vferman
Date : January 11 2021, 05:14 PM

I hope this helps you . Even though ElementTree has limited XPath support, it should be sufficient enough to do what you want...
XML Input (test.xml)
<doc>
    <NotificationPayload>
        <AnyOfferChangedNotification>
            <Offers>
                <Offer>
                    <SellerId>A2LZYV</SellerId>
                    <SubCondition>new</SubCondition>
                    <SellerFeedbackRating>
                        <SellerPositiveFeedbackRating>100</SellerPositiveFeedbackRating>
                        <FeedbackCount>929</FeedbackCount>
                    </SellerFeedbackRating>
                    <ShippingTime minimumHours="24" maximumHours="48" availabilityType="NOW"/>
                    <ListingPrice>
                        <Amount>16.69</Amount>
                        <CurrencyCode>USD</CurrencyCode>
                    </ListingPrice>
                    <Shipping>
                        <Amount>0.00</Amount>
                        <CurrencyCode>USD</CurrencyCode>
                    </Shipping>
                    <ShipsFrom>
                        <Country>US</Country>
                        <State>FL</State>
                    </ShipsFrom>
                    <IsFulfilledByAmazon>false</IsFulfilledByAmazon>
                    <IsBuyBoxWinner>false</IsBuyBoxWinner>
                    <PrimeInformation>
                        <IsPrime>false</IsPrime>
                        <IsNationalPrime>false</IsNationalPrime>
                    </PrimeInformation>
                    <IsFeaturedMerchant>true</IsFeaturedMerchant>
                    <ShipsDomestically>true</ShipsDomestically>
                </Offer>
            </Offers>            
        </AnyOfferChangedNotification>
    </NotificationPayload>
</doc>
import xml.etree.ElementTree as ET

root = ET.parse("test.xml")

SellerId = "A2LZYV"

for price in root.findall(f".//Offer[SellerId='{SellerId}'][SubCondition='new']/ListingPrice/Amount"):
    print(price.text)
16.69

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Find specific dictionary element without looping


Tag : python , By : user121501
Date : March 29 2020, 07:55 AM
this one helps. Your data structure doesn't support O(1) lookups, so you still have to loop through it:
any(d['Name'] == 'Dave' for d in dicts)
from collections import defaultdict

total = defaultdict(set)

for d in dicts:
    for key, value in d.items():
        total[key].add(value)
'Dave' in total['Name']

looping through element of XDocument and getting specific attributes


Tag : chash , By : micate
Date : March 29 2020, 07:55 AM
I wish this helpful for you You want to use XElement.Elements() to iterate through all child elements of your requests element, then use XElement.Attribute(XName name) to fetch the specified attribute by name.
You might also consider explicitly casting your XAttribute to a string rather than using the Value property, as the former will return null on a missing attribute rather than generating a null reference exception.
var propertiesRequested = XDocument.Parse(propertiesConfiguration);
var requests = propertiesRequested.Element("ModuleRequests");
foreach (var request in requests.Elements())
{
    var propertyValue = (string)request.Attribute("Id");

    if (systemProperties.ContainsKey(propertyValue) == false)
    {
        systemProperties.Add(propertyValue, (string)request.Attribute("Request"));
    }
}

Use XPATH to locate a specific element and then move forward from that element to locate the next table in the tree


Tag : html , By : Vasiliy
Date : March 29 2020, 07:55 AM
hope this fix your issue For your HTML, adjusted to be well-formed XML, and formatted for ease of reading:
<html> 
  <div>
    <p>maybe some words</p>
  </div>  
  <div/>  
  <div>
    <font>PICKLES are selling well</font>
  </div>  
  <div>
    <p>maybe some words</p>
    <table>
      <tr>
        <td>123</td>
      </tr>
    </table>
  </div> 
</html>
//font[contains(text(),"PICKLES")]/following::table[1]
for e in test_tree.xpath(('//font[contains(text(),"PICKLES")]'):
    e_text = e.text_content()  #to illustrate that I can do something with this element
    my_table = e.xpath('./following::table[1]')[0]  #while only one table is found a list is returned with the table as the only element of the list

Looping through list of single-element tuple yields different result than looping through multi-element tuple


Tag : python , By : mgz
Date : March 29 2020, 07:55 AM
this will help I have sqlite queries that output lists of tuples. I'm running into a situation that I don't understand why looping through a list of single-element tuples yields a different output compared to looping through a list of multi-element tuples. Take the following lists as an example: , You are not comparing apple to apple.
In [8]: for item in list1:
   ...:     print(item)

('value1',)
('value2',)

In [9]: for item in list2:
   ...:     print(item)

('value1', 'value1')
('value2', 'value2')

PHP - get specific element form each sub array without looping


Tag : php , By : platformNomad
Date : March 29 2020, 07:55 AM
Related Posts Related QUESTIONS :
  • how to prevent a for loop from overwriting a dictionary?
  • How To Fix: RuntimeError: size mismatch in pyTorch
  • Concatenating two Pandas DataFrames while maintaining index order
  • Why does this not run into an infinite loop?
  • Python Multithreading no current event loop
  • Ignore Nulls in pandas map dictionary
  • How do I get scrap data from web pages using beautifulsoup in python
  • Variable used, golobal or local?
  • I have a regex statement to pull all numbers out of a text file, but it only finds 77 out of the 81 numbers in the file
  • How do I create a dataframe of jobs and companies that includes hyperlinks?
  • Detect if user has clicked the 'maximized' button
  • Does flask_login automatically set the "next" argument?
  • Indents in python 3
  • How to create a pool of threads
  • Pandas giving IndexError on one dataframe but not on another similar dataframe
  • Django Rest Framework - Testing client.login doesn't login user, ret anonymous user
  • Running dag without dag file in airflow
  • Filling across a specified dimension of a numpy array
  • Python populating dataframe in pandas from text files
  • How to interpolate a single ("non-piecewise") cubic spline from a set of data points?
  • Divide 2 integers (leetcode 29) - recursion issue
  • Can someone explain why do I get this output in Python?
  • How do I scrape pdf and html from search results without obvious url
  • Is there a way to automatically make a "collage" of plots with matplotlib?
  • How to combine multiple rows in pandas with shared column values
  • How do I get LOAD_CLASSDEREF instruction after dis.dis?
  • Django - How to add items to Bootstrap dropdown?
  • Linear Regression - Does the below implementation of ridge regression finding coefficient term using gradient method is
  • How to drop all rows in pandas dataframe with negative values?
  • Most Efficient Way to Find Closest Date Between 2 Dataframes
  • Execution error when Passing arguments to a python script using os.system. The script takes sys.argv arguments
  • Looping through a function
  • Create a plot for each unique ID
  • a thread python with 'while' got another thread never start
  • Solution from SciPy solve_ivp contains oscillations for a system of first-order ODEs
  • trigger python events driven by selenium controlled browser
  • Passing line-edits to a contextmanager to set validators
  • Python: globals().items() iterations try to change a dict
  • Is it possible to specify starting values for each parameter (instead of bounds) for scipy's differential evolution?
  • why datetime.now() and constructed datetime using all fields(like year,month...) of now has big timedelta?
  • MySQL multiple table UPDATE query using sqlalchemy core?
  • find if a semantic version is superset of of another version python
  • Type checking against dynamically created objects
  • Struggling with simple reverse function
  • Is there a function for finding the midpoint of n points on sklearn.neighbors.NearestNeighbors?
  • How to set max number of tweets to fetch
  • PYTHON 3.7.4 NOT USING SQLITE 3.29.0
  • How to replace Nan value with zeros in a numpy array?
  • How to speed up calculating variance among sparse matrix
  • cupy code is not fast enough compared with numpy
  • How to count frequency of select values in Python pandas dataframe
  • Scrape Span Text from Google
  • Python watchdog, watch a directory and rename file on event.modification
  • Filtering rows in DataFrame with dependent conditions
  • How to check if a character is a not a part of number or URL in string?
  • Compare corresponding elements of a list
  • Python misinterprets 3 character string as UTF-8 continuation byte
  • Merge two columns in Pandas
  • Side Effect error in Python in an online compiler
  • How to convert a navigation list with depth levels to a parent-child flat list?
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com