我需要检查xml文件中是否存在某个标记。
例如,我想查看此代码段中是否存在标记:
<main>
<elem1/>
<elem2>Hi</elem2>
<elem3/>
...
</main>
目前,我正在使用一个带有错误检查的丑陋黑客,如下所示:
try:
if root.elem1.tag:
foo = elem1
except AttributeError:
foo = "error finding elem1"
如果字符串找不到节点(即“找不到-tagname-”),我还想自定义它。
我必须检查一长串变量,我不想重复代码100次。
有什么建议吗?
编辑:
下面是实际xml文件的一个片段:
<main>
<asset name="Virtual Dvaered Unpresence">
<virtual/>
<presence>
<faction>Dvaered</faction>
<value>-1000.000000</value>
<range>0</range>
</presence>
</asset>
<asset name="Virtual Empire Small">
<virtual/>
<presence>
<faction>Empire</faction>
<value>100.000000</value>
<range>2</range>
</presence>
</asset>
</main>
我想检查这个标签是否存在,如果存在的话,我想获取内容。
编辑编辑: 好吧,我要把两个答案合并起来,但我只能投一个。对不起的。
编辑3:关于XPath的相关问题:Python lxml (objectify): Xpath troubles
假设您想得到elem2的值,可以使用xpath来查找它。
hasattr()
适用于:编辑:更新了示例文件的答案。
我假设你想搜索每个资产的特定标签。如果是这样的话,以下几点对我有效:
结果是:
相关问题 更多 >
编程相关推荐