這是一個ElementTree Element
object。
你也可以看看lxml API documentation,它有一個lxml.etree._Element
page。該頁面告訴您關於您可能想知道的該類的每個屬性和方法。但是,我想先閱讀lxml.etree
tutorial。
但是,如果元素不能被索引,那麼它是一個空標記,並且沒有要檢索的子節點。
要找到Bernardo
的所有行,需要一個XPath表達式和一個名稱空間映射。不要緊,什麼前綴您使用,只要它是一個非空字符串lxml
將其映射到正確的名稱空間網址:
nsmap = {'s': 'http://www.tei-c.org/ns/1.0'}
for line in tree.xpath('.//s:sp[@who="Barnardo"]/s:l/text()', namespaces=nsmap):
print line.strip()
這在提取元素<l>
所有文本中包含的<sp who="Barnardo">
標籤。請注意標記名稱上的s:
前綴,nsmap
字典會告訴lxml
要使用的名稱空間。我打印了這些沒有周圍額外的空白。
爲您的樣品文件,給出了:
>>> for line in tree.xpath('.//s:sp[@who="Barnardo"]/s:l/text()', namespaces=nsmap):
... print line.strip()
...
Who's there?
Long live the king!
He.
'Tis now struck twelve; get thee to bed, Francisco.
Have you had quiet guard?
Well, good night.
If you do meet Horatio and Marcellus,
The rivals of my watch, bid them make haste.
Say,
What, is Horatio there?
Welcome, Horatio: welcome, good Marcellus.
I have seen nothing.
Sit down awhile;
And let us once again assail your ears,
That are so fortified against our story
What we have two nights seen.
Last night of all,
When yond same star that's westward from the pole
Had made his course to illume that part of heaven
Where now it burns, Marcellus and myself,
The bell then beating one,
In the same figure, like the king that's dead.
Looks 'a not like the king? mark it, Horatio.
It would be spoke to.
See, it stalks away!
How now, Horatio! you tremble and look pale:
Is not this something more than fantasy?
What think you on't?
I think it be no other but e'en so:
Well may it sort that this portentous figure
Comes armed through our watch; so like the king
That was and is the question of these wars.
'Tis here!
It was about to speak, when the cock crew.
嘗試:'etree.tostring(XML)' –
大,這樣的作品,但我怎麼從一個特定的標籤數據? – Jono
@Jono:如果你展示了'ham.xml'的內容,或者它至少是一個非常大的樣本,那麼幫助你會容易得多。 –