代码之家  ›  专栏  ›  技术社区  ›  user366312

如何仅使用一个函数读取3种XML文件?

  •  -1
  • user366312  · 技术社区  · 4 年前

    假设我有以下3种XML文件:

    file1.xml

    <memberdef>
        <param>
            <type>abc12300xyz__param -> type</type>
        </param>
    </memberdef>
    

    file2.xml

    <memberdef>
        <param>
            <type>abc12300xyz__param -> type</type>
            <declname>abc12300xyz__param -> declname</declname>
        </param>
    </memberdef>
    

    file3.xml

    <memberdef>
        <param>
            <type>
                <ref refid="abc12300xyz__refid" kindref="abc12300xyz__kindref">abc12300xyz -> ref</ref>
            </type>
            <declname>abc12300xyz__param -> declname</declname>
        </param>
    </memberdef>
    

    假设,我想用 LXML .

    文件1.xml 加载时,以下源代码失败:

    if memberdef.param.type.ref != None:
        ... ... ...
        ... ... ...
    

    1 回复  |  直到 4 年前
        1
  •  1
  •   zx485 potemkin    4 年前

    您可以使用这个简单的XPath检查元素是否存在(replace fileX.xml ). 如果元素存在于给定的XML文件中,XPath表达式只返回非空结果。在下面的例子中,测试从非常具体到更一般:

    from lxml import etree
    
    print("Checking variants...")
    root = etree.parse("fileX.xml")
    if root.xpath('/memberdef[param[type/ref and declname]]'):
        print("Third variant.")
    elif root.xpath('/memberdef[param[type and declname]]'):
        print("Second variant.")
    elif root.xpath('/memberdef/param[type]'):
        print("First variant.")
    else:
        print("None of the given variants.")
    

    所以呢

    • memberdef 元素具有 param 有孩子的孩子 type/ref 孩子和孩子 declname
    • 成员定义 有孩子的孩子 type declname公司
    • 第三个IF检查 成员定义 有孩子的孩子 类型 孩子。

    推荐文章