xpath 中的地址属性(都柏林核心)

Address attribute in with xpath (dublin core)

我有以下 XML-通过都柏林核心 SRU 的响应(其中有几个,这是一个例子):

<dc:title>Die EU im Einsatz gegen den Klimawandel : der EU-Emissionshandel - ein offenes System, das weltweit Innovationen fördert / [Europäische Kommission]</dc:title>
<dc:creator>Europäische Kommission</dc:creator>
<dc:publisher>[Luxemburg] : [Amt für Amtliche Veröff. der Europ. Gemeinschaften]</dc:publisher>
<dc:date>2005</dc:date>
<dc:language>ger</dc:language>
<dc:identifier xmlns:tel="http://krait.kb.nl/coop/tel/handbook/telterms.html" xsi:type="tel:ISBN">92-894-9187-6 geh.</dc:identifier>
<dc:identifier xsi:type="dnb:IDN">992017882</dc:identifier>
<dc:subject>360 Soziale Probleme, Sozialdienste, Versicherungen</dc:subject>
<dc:subject>330 Wirtschaft</dc:subject>
<dc:format>20 S.</dc:format>
</dc></recorddata><recordposition>3</recordposition></record>

我正在尝试解决元素 992017882,但我似乎无法正确执行此操作.因为我有几个这样的记录,有些有 2 个,一些 1 个,一些 3 个或更多 dc:identifier 版本,我正在使用一个函数来获取我需要的 xml 标签的内容并正在解析之后将其添加到数据框。这适用于 dc:title 等元素,但当我还需要处理属性时,我不知所措。我尝试了各种方法,但似乎对我需要解决两个名称空间(?)这一事实存在疑问。当前函数如下所示:

def parse_record(record):
    
    ns = {"dc": "http://purl.org/dc/elements/1.1/"}
    xml = ET.fromstring(unicodedata.normalize("NFC", str(record)))
    
    #idn
    idn = xml.xpath(".//dc:identifier[@xsi:type='dnb:IDN']", namespaces=ns)
    
    try:
        idn = idn.text
    except:
        idn = 'fail'
    
    # titel
    titel = xml.xpath('.//dc:title', namespaces=ns)
    
    try:
        titel = titel[0].text
        #titel = unicodedata.normalize("NFC", titel)
    except:
        titel = "unkown"
        
    meta_dict = {"idn":idn, "titel":titel}
    
    return meta_dict

我可以 运行 该函数没有任何问题,但是当我尝试使用以下代码将响应解析为数据帧时:

output = [parse_record(record) for record in records]
df = pd.DataFrame(output)
df

我收到错误消息:“XPathEvalError:未定义的命名空间前缀”

有人能帮忙吗?

正如评论中所指出的,包含命名空间声明的字典也应该包括 xsi 前缀的定义:

ns = {
        "dc": "http://purl.org/dc/elements/1.1/", 
        # should be changed depending on the namespace
        "xsi": "http://www.w3.org/2001/XMLSchema-instance" 
}