簡體   English   中英

使用 ETREE 解析 XML:查找“xl”元素屬性

[英]Parsing XML with ETREE: finding 'xl' element properties

我在下面有(縮寫的)XML 文件(我還稍微更改了該元素名稱以模糊應用程序)。

<?xml version="1.0" encoding="UTF-8" ?>
<Workplace Type="PP-1"
            Version="0.2"
            xmlns:xl="http://www.w3.org/1999/xlink">
    <Template xl:actuate="perFile"
                xl:href="../templates/opt/CMPRfile"
                xl:show="none"
                xl:title="CPP1"
                xl:type="verycomplicated"/>
    <ProjectID xl:actuate="withtrain"
                xl:href="filename.ppp"
                xl:show="none"
                xl:type="evenmorecomplicated"/>
/>


我想用 ETREE 解析 XML 文件並找到“xl:”元素的值。 我該怎么做。 似乎不是屬性或文本。 這是某種特殊屬性嗎? 例如,我嘗試使用如下代碼找到“href”的值。

我試圖查找並找出“xl”標簽是什么,但沒有運氣。 同樣奇怪的是,當我打印“Workplace”節點的屬性時,我得到的是“Type”和“Version”,但不是“xmlns”。 所以,我懷疑這是某種特殊屬性? 這是我第一次進行認真的 XML 解析,所以我可能在這里遺漏了一些東西。

我試過這個:

    xml_namespace = "{http://www.w3.org/1999/xlink}"
    tree = ET.parse(project_file_name)
    xml_root_element = tree.getroot()

    projectid_element = xml_root_element.find(xml_namespace + 
    "ProjectId")
    
    # Doesn't work
    value = projectid_element.text 
    value = projectid_element.attrib["href"]
    value = projectid_element.attrib["xl:href"]

    print("Value: " + value)

我期待值 'filename.ppp'

編輯 20221221_1557:

我確實看過 FordPerfect 提到的文章,但我似乎仍然無法提取這些值。 我有這段代碼:


    tree, ns = parse_and_get_ns(project_file_name)
    xml_root_element = tree.getroot()
    print("xml_root_element type: " + str(type(xml_root_element)))
    print("Namespaces found: ")
    print(ns)
    elements = xml_root_element.iterfind("xl:href", ns)
    print("elements type: " + str(type(elements)))
    for ele in elements:
        print("elements ele object type: " + str(type(ele)))

我得到這個作為輸出:

xml_root_element type: <class 'xml.etree.ElementTree.Element'>
Namespaces found:
{'xl': '{http://www.w3.org/1999/xlink}'}

所以你可以看到我正在迭代的根元素確實是一個元素,並且最終結果不包含任何對象。 但是,我確實希望至少有 1 個在那里。

經過一番擺弄后,我發現這些元素是關鍵。 您可以通過對元素使用方法 keys() 來獲取它們,如下所示:

xml_element = root.find(
        xml_namespace + "Model_Segment"
    ) # One of the elements in the XML example

    keys = xml_element.keys()
    for key in keys:
        print("key: " + key)

輸出:

密鑰:{http://www.w3.org/1999/xlink}href

密鑰:{http://www.w3.org/1999/xlink}標簽

關鍵:{http://www.w3.org/1999/xlink}角色

鍵:{http://www.w3.org/1999/xlink}title

密鑰:{http://www.w3.org/1999/xlink}類型

我還將把來自 FordPerfect 的答案標記為答案,因為它在這個問題的上下文中包含非常有用的信息。

編輯:忘記我寫的東西!

看看這個答案:
https://stackoverflow.com/a/14853417/10576322

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM