簡體   English   中英

XML無法在Python中返回正確的子標記/數據

[英]XML not returning correct child tags/data in Python

您好,我正在打電話要求從網上商店退回訂單數據。 我的問題是,一旦將數據傳遞給根變量,iter方法就不會返回正確的結果。 例如,顯示多個同名而不是一個的標簽,並且不顯示標簽內的數據。

我認為這是由於XML格式不正確,所以我通過使用pretty_print將其保存到文件中來對其進行了格式化,但這並沒有解決錯誤。

我該如何解決? - 提前致謝

碼:

import requests, xml.etree.ElementTree as ET, lxml.etree as etree

url="http://publicapi.ekmpowershop24.com/v1.1/publicapi.asmx"
headers = {'content-type': 'application/soap+xml'}
body = """<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
  <soap12:Body>
    <GetOrders xmlns="http://publicapi.ekmpowershop.com/">
      <GetOrdersRequest>
        <APIKey>my_api_key</APIKey>
        <FromDate>01/07/2018</FromDate>
        <ToDate>04/07/2018</ToDate>
      </GetOrdersRequest>
    </GetOrders>
  </soap12:Body>
</soap12:Envelope>"""

#send request to ekm
r = requests.post(url,data=body,headers=headers)

#save output to file
file = open("C:/Users/Mark/Desktop/test.xml", "w")
file.write(r.text)
file.close()

#take the file and format the xml
x = etree.parse("C:/Users/Mark/Desktop/test.xml")
newString = etree.tostring(x, pretty_print=True)
file = open("C:/Users/Mark/Desktop/test.xml", "w")
file.write(newString.decode('utf-8'))
file.close()

#parse the file to get the roots
tree = ET.parse("C:/Users/Mark/Desktop/test.xml")
root = tree.getroot()

#access elements names in the data
for child in root.iter('*'):
    print(child.tag)

#show orders elements attributes
tree = ET.parse("C:/Users/Mark/Desktop/test.xml")
root = tree.getroot()
for order in root.iter('{http://publicapi.ekmpowershop.com/}Order'):
    out = {}
    for child in order:
        if child.tag in ('OrderID'):
        out[child.tag] = child.text
    print(out)

元素輸出:

{http://publicapi.ekmpowershop.com/}Orders
{http://publicapi.ekmpowershop.com/}Order
{http://publicapi.ekmpowershop.com/}OrderID
{http://publicapi.ekmpowershop.com/}OrderNumber
{http://publicapi.ekmpowershop.com/}CustomerID
{http://publicapi.ekmpowershop.com/}CustomerUserID
{http://publicapi.ekmpowershop.com/}Order
{http://publicapi.ekmpowershop.com/}OrderID
{http://publicapi.ekmpowershop.com/}OrderNumber
{http://publicapi.ekmpowershop.com/}CustomerID
{http://publicapi.ekmpowershop.com/}CustomerUserID

訂單輸出:

{http://publicapi.ekmpowershop.com/}Order {}
{http://publicapi.ekmpowershop.com/}Order {}

格式化后的XML結構:

 <soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <soap:Body>
    <GetOrdersResponse xmlns="http://publicapi.ekmpowershop.com/">
      <GetOrdersResult>
        <Status>Success</Status>
        <Errors/>
        <Date>2018-07-10T13:47:00.1682029+01:00</Date>
        <TotalOrders>10</TotalOrders>
        <TotalCost>100</TotalCost>
        <Orders>
          <Order>
            <OrderID>100</OrderID>
            <OrderNumber>102/040718/67</OrderNumber>
            <CustomerID>6910</CustomerID>
            <CustomerUserID>204</CustomerUserID>
            <FirstName>TestFirst</FirstName>
            <LastName>TestLast</LastName>
            <CompanyName>Test Company</CompanyName>
            <EmailAddress>test@Test.com</EmailAddress>
            <OrderStatus>Dispatched</OrderStatus>
            <OrderStatusColour>#00CC00</OrderStatusColour>
            <TotalCost>85.8</TotalCost>
            <OrderDate>10/07/2018 14:30:43</OrderDate>
            <OrderDateISO>2018-07-10T14:30:43</OrderDateISO>
            <AbandonedOrder>false</AbandonedOrder>
            <EkmStatus>SUCCESS</EkmStatus>
          </Order>
        </Orders>
        <Currency>GBP</Currency>
      </GetOrdersResult>
    </GetOrdersResponse>
  </soap:Body>
</soap:Envelope>

檢查標簽時,需要考慮名稱空間。

>>> # Include the namespace part of the tag in the tag values that we check.
>>> tags = ('{http://publicapi.ekmpowershop.com/}OrderID', '{http://publicapi.ekmpowershop.com/}OrderNumber')
>>> for order in root.iter('{http://publicapi.ekmpowershop.com/}Order'):
...     out = {}
...     for child in order:
...         if child.tag in tags:
...             out[child.tag] = child.text
...     print(out)
... 
{'{http://publicapi.ekmpowershop.com/}OrderID': '100', '{http://publicapi.ekmpowershop.com/}OrderNumber': '102/040718/67'}

如果您不希望在輸出中使用名稱空間前綴,則可以通過僅在}字符之后包含標記的那一部分來去除它們。

>>> for order in root.iter('{http://publicapi.ekmpowershop.com/}Order'):
...     out = {}
...     for child in order:
...         if child.tag in tags:
...             out[child.tag[child.tag.index('}')+1:]] = child.text
...     print(out)
... 
{'OrderID': '100', 'OrderNumber': '102/040718/67'}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM