使用Python从XML名称值列表中提取数据

时间:2017-11-03 00:17:24

标签: python xml beautifulsoup

我一直在尝试从XML响应中提取某些数据。我能够得到某些标签,但我需要的信息是一种不同的格式,我没有运气。我将以下XML存储为变量itemspecifics。我需要的是Manufacturer Part Number的值90105-MV9-003。我不明白的是如何提取这些数据,因为标签名称<name>重复了。

>>> print itemspecifics
<itemspecifics><namevaluelist><name>Brand</name><value>Honda</value>
<source>ItemSpecific</source></namevaluelist><namevaluelist>
<name>Country/Region of Manufacture</name><value>Japan</value>
<source>ItemSpecific</source></namevaluelist><namevaluelist>
<name>Manufacturer Part Name</name><value>BOLT, DISK (8X24) (TSUKIBOSHI)
</value><source>ItemSpecific</source></namevaluelist><namevaluelist>
<name>Manufacturer Part Number</name><value>90105-MV9-003</value>
<source>ItemSpecific</source></namevaluelist><namevaluelist><name>Placement 
on Vehicle</name><value>Rear</value><source>ItemSpecific</source>
</namevaluelist><namevaluelist><name>Retail Price</name>
<value>$20.96</value><source>ItemSpecific</source></namevaluelist>
<namevaluelist><name>Type</name><value>rear rotor bolt set</value>
<source>ItemSpecific</source></namevaluelist></itemspecifics>
>>> 
>>> print(type(itemspecifics))
<class 'bs4.element.Tag'>

1 个答案:

答案 0 :(得分:1)

使用ElementTree

更容易解析XML
public boolean deleteCreditCategory(int creditCategoryId) {
    if(isCreditCategoryDeletable(creditCategoryId)) {
        // TODO DEBUG this: The query function is always returning an Empty set
        Cursor c = database.query(CREDIT_CATEGORY_TABLE,new String[] {CREDIT_CATEGORY_IMAGE,CREDIT_CATEGORY_ID},CREDIT_CATEGORY_ID+"=?",new String[] {creditCategoryId+""},null,null,null);
        if (Cursor.moveTofirst) {
            int imageid = c.getInt(c.getColumnIndex(CREDIT_CATEGORY_IMAGE));
            database.beginTransaction();
            if (database.delete(CREDIT_CATEGORY_TABLE,CREDIT_CATEGORY_ID+" = ?",new String[] {creditCategoryId+""}) == 1) {
                if( this.deleteImage(imageId) ) {
                    database.setTransactionSuccessful();
                    database.endTransaction();
                    return true;
                }
            }
            database.endTransaction();
        }
    }
    return false;
}