Python讀取XML設定檔小例子

來源:互聯網
上載者:User
設定檔如下,名字為config.xml
<?xml version="1.0"?>
<config>
    <server>server1</server>
    <server>server2</server>
    <account>account</account>
    <pwd>pwd</pwd>
</config>

Python代碼如下:
from xml.dom.minidom import parse, parseString

def getText(nodelist):
    rc = ""
    for node in nodelist:
        if node.nodeType == node.TEXT_NODE:
            rc = rc + node.data
    return rc

if __name__=="__main__":
    dom1 = parse('config.xml') # parse an XML file by name

    config_element = dom1.getElementsByTagName("config")[0]
    servers = config_element.getElementsByTagName("server")
    for server in servers:
        print getText(server.childNodes)

顯示結果:
mail.hundsun.com
mail.hundsun.comdd

Python讀取XML設定檔還是比較簡單的,主要是perse的getElementsByTagName()函數,它返回的是NodeList對象。
Python 的Library Reference上如下解釋NodeList:

A NodeList represents a sequence of nodes. These objects are used in two ways in the DOM Core recommendation: the Element objects provides one as its list of child nodes, and the getElementsByTagName() and getElementsByTagNameNS() methods of Node return objects with this interface to represent query results.

對NodeList中的每個Node,調用getText函數,如果是TEXT_NODE類型的,則將其列印出。
Node的childNodes的說明如下:

childNodes
A list of nodes contained within this node. This is a read-only attribute.

DOM的常用節點:
節點類型                                  例子
Document type                    <!DOCTYPE food SYSTEM "food.dtd">
Processing instruction              <?xml version="1.0"?>
Element                          <drink type="beer">Carlsberg</drink>
Attribute                          type="beer"
Text                               Carlsberg

Node 有個nodeValue屬性,開始不知道和node的data屬性有何差別,後來查了DOM的文檔,如下解釋:
XML 對象的節點值。如果 XML 對象是一個文本節點,則 nodeType 為 3,nodeValue 是節點的文本。如果 XML 對象是一個 XML 元素(nodeType 為 1),則 nodeValuenull 且唯讀

在Python裡試了一下,對普通的文本節點,如“<server>mail.</server>”,nodeValue是1,為了要顯示其常值內容,用.data屬性和用.nodeValue屬性是效果一樣的,如:
            rc = ""
            for node in node.childNodes:
                if node.nodeType in ( node.TEXT_NODE, node.CDATA_SECTION_NODE):
                    rc = rc + node.nodeValue
                print rc

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.