【问题标题】:Find nodes defined in corrupted namespace查找在损坏的命名空间中定义的节点
【发布时间】:2016-10-01 09:08:11
【问题描述】:

我已经下载了this XML 文件。

我正在尝试获取includingNote,如下所示:

...
namespaces = { "skos" : "http://www.w3.org/2004/02/skos/core#", "xml" : "http://www.w3.org/XML/1998/namespace", 
                 "udc" : "http://udcdata.info/udc-schema#" }
...


includingNote = child.find("udc:includingNote[@xml:lang='en']", namespaces)
if includingNote:
  print includingNote.text.encode("utf8")

该方案位于here,似乎已损坏。

有没有办法可以为每个子节点打印includingNote

【问题讨论】:

    标签: python xml xml-namespaces elementtree


    【解决方案1】:

    在udc-scheme中确实没有声明skos前缀,但是搜索XML文档是没有问题的。

    以下程序提取 639 个includingNote 元素:

    from xml.etree import cElementTree as ET
    
    namespaces = {"udc" : "http://udcdata.info/udc-schema#",
                  "xml" : "http://www.w3.org/XML/1998/namespace"}
    
    doc = ET.parse("udcsummary-skos.rdf")
    includingNotes = doc.findall(".//udc:includingNote[@xml:lang='en']", namespaces)
    
    print len(includingNotes)   # 639
    
    for i in includingNotes:
        print i.text
    

    注意在元素名称前使用findall().//,以便搜索整个文档。


    这是一个变体,它通过首先找到所有 Concept 元素来返回相同的信息:

    from xml.etree import cElementTree as ET
    
    namespaces = {"udc" : "http://udcdata.info/udc-schema#",
                  "skos" : "http://www.w3.org/2004/02/skos/core#",
                  "xml" : "http://www.w3.org/XML/1998/namespace"}
    
    doc = ET.parse("udcsummary-skos.rdf")
    concepts = doc.findall(".//skos:Concept", namespaces)
    
    for c in concepts:
        includingNote = c.find("udc:includingNote[@xml:lang='en']", namespaces)
        if includingNote is not None:
            print includingNote.text
    

    注意is not None 的使用。没有它,它就行不通。这似乎是 ElementTree 的一个特性。见Why does bool(xml.etree.ElementTree.Element) evaluate to False?

    【讨论】:

    • len(包括Notes) 打印0
    • 嗯,它对我有用。请提供更多详细信息。你使用什么版本的 Python?我用的是 2.7.12。
    猜你喜欢
    • 2020-05-21
    • 1970-01-01
    • 2012-11-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-16
    • 2011-06-09
    • 1970-01-01
    • 2011-06-18
    相关资源
    最近更新 更多