通过ElementTree解析XML标记的属性值并替换值字符串

时间:2016-08-12 21:42:11

标签: python xml parsing elementtree

我是Python新手并尝试自动完成任务。我花了两天时间阅读文档,查看了其他各种类似的问题,但是现在,我已经碰壁了,无法继续前进。

我觉得Elementtree模块上没有详细记录Python文档。也许这只是我。另外,我知道我可以使用其他模块。但请指导我只使用Elementtree。请帮我指导。

任务是解析XML并使用Elementtree替换所有标记的属性值。在web-server-parm中,我需要替换包含" http://api-stg.link.com的所有链接。"对于前...

FROM

" ServerAddr =" http://api-stg.link.com/dataapi/v2/exchangerates/"

" 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&amp;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&amp;limit=9999999" timedOut="10000" X-API-UserId="gdfsgvhdgjfjuhgdyejhgsfegtb" X-API-ProductId="ADS" ApiKey="@gggf-fsffff@"/>
  </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")

1 个答案:

答案 0 :(得分:1)

考虑在元素之间使用iter()条件if替换:

import xml.etree.ElementTree as ET 

#----------------------------------------------------------------------
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()")

    for serv in root.iter('server'):
        for web in serv.iter('web-server-parm'):
                if 'http://api-stg.link.com' in web.get('ServerAddr'):
                    web.set('ServerAddr', web.get('ServerAddr').\
                        replace("http://api-stg.link.com", "http://api-DATA-stg.link.com"))

    print(ET.tostring(root).decode("UTF-8"))

    tree.write("ConfigRoot_py.xml")

# #----------------------------------------------------------------------
if __name__ == "__main__":
    parseXML("ConfigRoot.xml")

<强>输出

<ConfigRoot>
  <max-layer layer="5" />
  <enabled-cache status="0" />
  <server type="fgrfreefr">
    <web-server-parm ApiKey="fgggdfvdffdgdfg" ServerAddr="http://api-DATA-stg.link.com/dataapi/v2/securities?response=complex&amp;limit=9999999" X-API-ProductId="ADS" X-API-UserId="54456464561" mode="QA" timedOut="10000" />
    <web-server-parm ApiKey="@gggf-fsffff@" ServerAddr="http://api-uat.link.com/dataapi/v2/securities?response=complex&amp;limit=9999999" X-API-ProductId="ADS" X-API-UserId="gdfsgvhdgjfjuhgdyejhgsfegtb" mode="UAT" timedOut="10000" />
  </server>
  <server type="vfffdg">
    <web-server-parm ApiKey="fgvdgggdfgttggefr" ServerAddr="http://api-DATA-stg.link.com/dataapi/v2/exchangerates/" X-API-ProductId="ADS" X-API-UserId="gsfsftfdfrfefrferf" mode="QA" timedOut="10000" />
    <web-server-parm ApiKey="@hdvfddfdd" ServerAddr="http://api-DATA-stg.link.com/dataapi/v2/exchangerates/" X-API-ProductId="ADS" X-API-UserId="gdfdagtgdfsgtrsdfsg" mode="UAT" timedOut="10000" />
  </server>
</ConfigRoot>