lxml xpath表达式,用于选择给定子节点(包括其子节点)下的所有文本

2024-04-20 02:06:13 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我有一个XML,如下所示:

<node1>
    <text title='book'>
       <div chapter='0'>
          <div id='theNode'>
              <p xml:id="40">
               A House that has:
                   <p xml:id="45">- a window;</p>
                   <p xml:id="46">- a door</p>
                   <p xml:id="46">- a door</p>
               its a beuatiful house
               </p>
          </div>
       </div>
    </text>
</node1>

我想定位文本标题,并从文本标题书节点中出现的第一个p标记获取所有文本

到目前为止,我知道:

from lxml import etree
XML_tree = etree.fromstring(XML_content,parser=parser)
text = XML_tree.xpath('//text[@title="book"]/div/div/p/text()') 

得到:“一座拥有美丽房子的房子”

但我也希望所有可能的孩子和第一个伟大孩子的所有文本出现在

基本上;查找然后查找第一个

,并给出该p标记下的所有文本,无论嵌套是什么

伪代码:

text = XML_tree.xpath('//text[@title="book"]/... any number of nodes.../p/ ....all text under p') 

谢谢


Tags: text标记文本dividtreeparser标题
2条回答

另一种选择:

XML_tree = etree.fromstring(XML_content)
text = [el.strip() for el in XML_tree.xpath('//text()[ancestor::text[@title="book"]][normalize-space()]')]
print(" ".join(text))
print("\n".join(text))

输出:

A House that has: - a window; - a door - a door its a beuatiful house
A House that has:
- a window;
- a door
- a door
its a beuatiful house

尝试使用^{}^{}

from lxml import etree

XML_content = """
<node1>
    <text title='book'>
       <div chapter='0'>
          <div id='theNode'>
              <p xml:id="x40">
               A House that has:
                   <p xml:id="x45">- a window;</p>
                   <p xml:id="x46">- a door</p>
                   <p xml:id="x47">- a door</p>
               its a beuatiful house
               </p>
          </div>
       </div>
    </text>
</node1>
"""

XML_tree = etree.fromstring(XML_content)
text = XML_tree.xpath('string(//text[@title="book"]/div/div/p)')
# text = XML_tree.xpath('normalize-space(//text[@title="book"]/div/div/p)')
print(text)

使用string()输出


               A House that has:
                   - a window;
                   - a door
                   - a door
               its a beuatiful house

使用normalize-space()输出

A House that has: - a window; - a door - a door its a beuatiful house

相关问题 更多 >