lxml doc.find返回无

时间:2016-06-02 08:30:24

标签: python xml lxml

我有这个xml输出,我想提取一些元素。

示例XML:

addressBook = []
def find(name):
    for i in addressBook:
        if i['nickname'] == name:
            return i
        else:
            continue

def add():
    contact = {}
    print("Enter 'cancel' to return to menu")
    nickname = str.lower(input('Enter the nickname: '))
    for i in addressBook:
        if i['nickname'] == nickname:
            print("Contact already exists!")
        else:
            continue
    if nickname.lower() == 'cancel':
        return None
    else:
        name = str.lower(input('Enter the full name: '))
        if name.lower() == 'cancel':
            return None
        address = str.lower(input('Enter the address: '))
        if address.lower() == 'cancel':
            return None
        phone = str.lower(input('Enter the phone number: '))
        if phone.lower() == 'cancel':
            return None
        contact['nickname'] = nickname
        contact['name'] = name
        contact['address'] = address
        contact['phone'] = phone
        return contact

def delete(name): #prompt for a nickname, then find and display the related entry. Ask if this is correct to delete
    for contact in addressBook:
        if contact['nickname'] == name:
            print(contact)
            addressBook[contact]
            print("Contact deleted!")
        else:
            print("Contact not found!")
            continue

def listAll():
    count = 0
    for i in addressBook:
        count += 1
        print(count,'\t', i, '\n')
    if addressBook == []:
        print("No contacts found!")

print("Welcome to your address book!")
print("***My Contacts***")
print("\t F = Find a contact")
print("\t A = Add new contact")
print("\t D = Delete a contact")
print("\t L = List all contacts")
print("\t Q = Quit")

while True:
    try:
        global command
        command = str.upper(input("Command: ? "))
        if command == 'F':
            result = find(str.lower(input('Enter nickname to find: ')))
            if result != None:
                resultString = ''
                for key,val in result.items():
                    resultString = resultString + str.title(key) + ': ' + str.title(val) + ' | '
                print(resultString)
            else:
                print('Contact not found!')
        elif command == 'A':
            while True:
                details = add()
                if details == None:
                    break
                else:
                    addressBook.append(details)
                    print("Contact added!")
        elif command == 'D':
            delete(str.lower(input('Enter nickname of contact to delete: ')))
        elif command == 'L':
            listAll()
        elif command == 'Q':
            exit()
            break
        else:
            print("Invalid command, please try again!")
            continue
    except:
        if command == 'Q':
            exit()

我尝试了以下代码段

代码

<?xml version="1.0" encoding="UTF-8"?>
<rpc-reply xmlns="urn:ietf:2.0" message-id="101">
  <data>
    <bl1 xmlns="http://example.com/ns/xyz/xxx-op">
      <A>
        <B>
          <C>
            <D>
              <E>0.0.0.0</E>
              <F>1200</F>
              <C>
                <G>0</G>
                <H>0</H>
                <I>0</I>
                <J>0</J>
                <K>0</K>
                <L>0</L>
                <M>0</M>
                <N>0</N>
                <O>0</O>
                <P>0</P>
                <Q>0</Q>
                <R>0</R>
                <S>0</S>
                <T>0</T>
                <U>0</U>
                <V>0</V>
                <W>0</W>
                <X>0</X>
              </C>
              <Y>1.1.1.1</Y>
              <Z>IPv6</Z>
            </D>
          </C>
        </B>
      </A>
    </bl1>
  </data>
</rpc-reply>

不知何故,这不起作用。 memoryElem正在打印无。 你能纠正我错在哪里吗?

2 个答案:

答案 0 :(得分:2)

您的目标元素位于默认命名空间中:

xmlns="http://example.com/ns/xyz/xxx-op"

您需要将前缀映射到默认命名空间URI,并使用该前缀来引用命名空间中的元素:

ns = {'d': 'http://example.com/ns/xyz/xxx-op'}
memoryElem = doc.find('.//d:Y', ns)
print memoryElem.text    

答案 1 :(得分:0)

这可能是命名空间问题。

您可以尝试BeautifulSoup

import bs4

soup = bs4.BeautifulSoup(open("sample.xml", "r").read(), features="xml")
yt = soup.find("Y").text
print(yt)

输出:

1.1.1.1