[英]How can i parse a xml file in python
我有一个xml文件(基本上该文件是jenkins从属config.xml文件),我必须从中获取某些值。 因此,我尝试使用Element Tree
来解析xml
文件,如下所示
tree = ET.parse(config.xml)
root = tree.getroot()
print root
for item in root.findall('slave'):
然后我将这个解析的xml
文件保存在一个文本文件中,现在我想获取此标记中的值,我可以通过bash
但是我想知道如何在python中做到这一点bash代码
cat test.xml | sed -n 's:.*<label>\(.*\)</label>.*:\1:p'
这是一个示例jenkins slave config.xml文件
<slave>
<name>some_name</name>
<description/>
<remoteFS>some_value</remoteFS>
<numExecutors>xx</numExecutors>
<mode>EXCLUSIVE</mode>
<retentionStrategy class="xxxx"/>
<launcher class="xxxxx" plugin="xxxxx">
<host>xxx.x.x.xx</host>
<port>xx</port>
<credentialsId>xxxxxxx-xxx-xxxx-xxxx-xxxxxxxxxxxx</credentialsId>
<maxNumRetries>0</maxNumRetries>
<retryWaitTime>0</retryWaitTime>
<sshHostKeyVerificationStrategy class="hudson.plugins.sshslaves.verifiers.NonVerifyingKeyVerificationStrategy/></launcher>
<label>some_label</label>
</slave>
与标签类似,我还需要其他值,例如主机名,端口等。
您可以使用.iter()
进行递归迭代以查找元素。 检查官方文档 。
这是一个slave
节点打印label
和host
文本的示例。
更新 :将code.py
修改为另外打印launcher
标签的class
属性值。 它使用element.attrib
获取标签的属性。 可以在解析XML的官方文档中找到更多信息。
test.xml
:
<slave>
<name>some_name</name>
<description/>
<remoteFS>some_value</remoteFS>
<numExecutors>xx</numExecutors>
<mode>xxx</mode>
<retentionStrategy class="xxxx"/>
<launcher class="xxxxx" plugin="xxxxx">
<host>xxx.x.x.xx</host>
<port>xx</port>
<credentialsId>xxxxxxxx</credentialsId>
<maxNumRetries>x</maxNumRetries>
<retryWaitTime>x</retryWaitTime>
<sshHostKeyVerificationStrategy class="hudson.plugins.sshslaves.verifiers.NonVerifyingKeyVerificationStrategy"/>
</launcher>
<label>somelabel</label>
</slave>
code.py
:
import xml.etree.ElementTree as ET
tree = ET.parse("test.xml")
root = tree.getroot()
for item in root.iter('slave'):
for label in item.iter("label"):
print label.text
for host in item.iter("host"):
print host.text
for launcher in item.iter("launcher"):
print launcher.attrib["class"]
输出:
somelabel
xxx.x.x.xx
xxxxx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.