Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/299.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何仅使用一个函数读取3种XML文件?_Python_Xml_Lxml_Lxml.objectify - Fatal编程技术网

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

Python 如何仅使用一个函数读取3种XML文件?,python,xml,lxml,lxml.objectify,Python,Xml,Lxml,Lxml.objectify,假设我有以下3种XML文件: file1.xml <memberdef> <param> <type>abc12300xyz__param -> type</type> </param> </memberdef> <memberdef> <param> <type>abc12300xyz__param -> type&l

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

file1.xml

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

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

在这种情况下我应该使用什么策略?

您可以使用这个简单的XPath检查元素是否存在(替换
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.")
所以

  • 第一个IF检查
    memberdef
    元素是否有
    param
    子元素,该子元素有
    type/ref
    子元素和
    declname
    子元素
  • 第二个IF only检查
    memberdef
    元素是否有
    param
    子元素,该子元素有
    type
    子元素和
    declname
    子元素
  • 第三个IF检查
    memberdef
    元素是否有
    param
    子元素,该子元素具有
    类型
    子元素
诸如此类,你应该了解要点