2016-12-28 52 views
1

我有下詹金斯API脚本:例如GET值包含XML

import jenkins 
import json 
import re 

server = jenkins.Jenkins('https://jenkins_url', username, password) 
nodes = json.dumps(server.get_nodes()) 
nodes = re.sub('\"offline\"|[:{} \[\]]|true,|false,|\"name\"|\"','',nodes).split(',') 
for label in nodes: 
    if label != 'master': 
     print label 
     node_config = server.get_node_config(label) 
     print node_config 

node_config包含下一XML文本:

<?xml version="1.0" encoding="UTF-8"?> 
<slave> 
    <name>test.server</name> 
    <description></description> 
    <remoteFS>/var/lib/jenkins</remoteFS> 
    <numExecutors>1</numExecutors> 
    <mode>EXCLUSIVE</mode> 
    <retentionStrategy class="hudson.slaves.RetentionStrategy$Always"/> 
    <launcher class="hudson.plugins.sshslaves.SSHLauncher" plugin="[email protected]"> 
    <host>test.server</host> 
    <port>7777</port> 
    <credentialsId>d0970a8f-d124</credentialsId> 
    <maxNumRetries>0</maxNumRetries> 
    <retryWaitTime>0</retryWaitTime> 
    </launcher> 
    <label>BuildServer</label> 
    <nodeProperties/> 
    <userId>test</userId> 
</slave> 

我想每个标签的价值以获得输出,例如test.server等

你能帮我吗?

回答

1
xml_text = """<?xml version="1.0" encoding="UTF-8"?> 
<slave> 
    <name>test.server</name> 
    <description></description> 
    <remoteFS>/var/lib/jenkins</remoteFS> 
    <numExecutors>1</numExecutors> 
    <mode>EXCLUSIVE</mode> 
    <retentionStrategy class="hudson.slaves.RetentionStrategy$Always"/> 
    <launcher class="hudson.plugins.sshslaves.SSHLauncher" plugin="[email protected]"> 
    <host>test.server</host> 
    <port>7777</port> 
    <credentialsId>d0970a8f-d124</credentialsId> 
    <maxNumRetries>0</maxNumRetries> 
    <retryWaitTime>0</retryWaitTime> 
    </launcher> 
    <label>BuildServer</label> 
    <nodeProperties/> 
    <userId>test</userId> 
</slave> 
""" 

import xml.etree.ElementTree 
root = xml.etree.ElementTree.fromstring(xml_text) 

# show only a particular tag 
for name in root.findall('name'): 
    print(name.text) 

# show all children at first level 
for child in root: 
    print('%s: %s' % (child.tag, child.text)) 

# build a dict (will only get last of any duplicate tags, and no children) 
slave = {child.tag: child.text for child in root} 

# build a dict (will only get last of any duplicate tags) 
def xml_todict(xml_node): 
    dict_ = {} 
    for child in xml_node: 
     dict_[child.tag] = xml_todict(child) 
    dict_.update(xml_node.attrib) 
    if not dict_: 
     return xml_node.text 
    if xml_node.text and 'text' not in dict_: 
     dict_['text'] = xml_node.text 
    return dict_ 

slave = xml_todict(root) 
+0

我工作,但它不打印我想要什么。 – user54

+0

它打印所有除: test.server d0970a8f-D124 0 0 user54

+0

我已经找到错误:而不是root.findall('name')我必须把root.findall('.// host')。根据文档“//”选择当前元素下的所有级别上的所有子元素(搜索整个子树)。例如,“。// egg”选择整个树中的所有“蛋”元素等。感谢您的帮助! – user54