私はPythonを初めて使い、タスクを自動化しようとしています。私は2日かけてドキュメントを読んで、他の同様の質問に目を通しましたが、今は壁に衝突して前進できません。ElementTreeを使ってXMLタグの属性値を解析し、値の文字列を置き換えます。
私は、PythonドキュメントがElementtreeモジュールで十分に文書化されていないと感じています。多分それは私だけです。また、私は他のモジュールを使用できることを知っています。しかしElementtreeだけで私を指示してください。私は手伝ってください。
このタスクは、XMLを解析し、Elementtreeを使用してすべてのタグの属性値を置き換えることです。 web-server-parmでは、「http://api-stg.link.com」を含むすべてのリンクを置き換える必要があります。元については...
FROM
"SERVERADDR =" http://api-stg.link.com/dataapi/v2/exchangerates/ "
TO" ServerAddr = "http://api-DATA-stg.link.com/dataapi/v2/exchangerates/"。
のXMLのtest.xml
<?xml version="1.0" encoding="utf-8"?>
<ConfigRoot>
<max-layer layer="5"/>
<enabled-cache status="0"/>
<server type="fgrfreefr">
<web-server-parm mode="QA" ServerAddr="http://api-stg.link.com/dataapi/v2/securities?response=complex&limit=9999999" timedOut="10000" X-API-UserId="54456464561" X-API-ProductId="ADS" ApiKey="fgggdfvdffdgdfg"/>
<web-server-parm mode="UAT" ServerAddr="http://api-uat.link.com/dataapi/v2/securities?response=complex&limit=9999999" timedOut="10000" X-API-UserId="gdfsgvhdgjfjuhgdyejhgsfegtb" X-API-ProductId="ADS" ApiKey="@[email protected]"/>
</server>
<server type="vfffdg">
<web-server-parm mode="QA" ServerAddr="http://api-stg.link.com/dataapi/v2/exchangerates/" timedOut="10000" X-API-UserId="gsfsftfdfrfefrferf" X-API-ProductId="ADS" ApiKey="fgvdgggdfgttggefr"/>
<web-server-parm mode="UAT" ServerAddr="http://api-uat.link.com/dataapi/v2/exchangerates/" timedOut="10000" X-API-UserId="gdfdagtgdfsgtrsdfsg" X-API-ProductId="ADS" ApiKey="@hdvfddfdd"/>
</server>
</ConfigRoot>
Task.py これは私がこれまで
import xml.etree.ElementTree as ET
# import XML, SubElement, Element, tostring
#----------------------------------------------------------------------
def parseXML(xml_file):
"""
Parse XML with ElementTree
"""
tree = ET.ElementTree(file=xml_file)
root = tree.getroot()
# get the information via the children!
print "Iterating using getchildren()"
node = root.getchildren()
for server_addr in node:
node_children = server_addr.getchildren()
for node_child in node_children:
print "_________passed__________"
print "%s=%s" % (node_child.attrib, node_child.text)
test = node_child.findtext("http://api-stg.link.com/dataapi/v2/exchangerates/")
if test is None:
continue
tests = test.text
print tests
# #----------------------------------------------------------------------
if __name__ == "__main__":
parseXML("test/test.xml")
あなたは文字通り交換する 'SERVERADDR = "のhttp:// api-stg.link.com/dataapi/V2/exchangerates/'SERVERADDR ='と" のhttp:// API -DATA-stg.link.com/dataapi/v2/exchangates/'?もしそうなら、あなたは単に置き換えを行うことを考えることができます: 'new_xml.replace( 'ServerAddr =" http://api-stg.link.com/dataapi/v2/exchangerates/ "、" ServerAddr = "http:// api- DATA-stg.link.com/dataapi/v2/exchangerates/ ') ' – Karin