Skip to main content
 首页 » 编程设计

python之使用 Python 解析 XML 并打印整个元素

2024年12月31日10shangdawei

这是我的第一个问题。通常我能找到我需要的东西,但经过一周的搜索和尝试后,我还在同一个地方,所以我需要你的帮助。

我有一本书,它位于一个超过 6000 行的大型 XML 文件中。我需要做的是取一个元素 <sec>并将其内容放入字符串中。有时该元素只有一个段落,有时它有更多,有时段落有列表和其他东西,我需要将所有这些都捕获到一个字符串中。

这里是一个如何格式化书籍的例子。

<book> 
    <book-body> 
        <book-part id="ch01" book-part-type="chapter"> 
            <book-part-meta> 
                <title-group> 
                    <label><target target-type="page" id="pg1"/>Chapter 1</label> 
                    <title>Some Title</title> 
                </title-group> 
            </book-part-meta> 
            <body> 
                <sec id="ch01lev1sec1" disp-level="level1"> 
                    <title>Introduction</title> 
                    <p>This is a <em>paragraph</em></p> 
                    <p>This is second paragraph 
                        <list list-type="bullet"> 
                        <list-item><p>List Item 1</p></list-item> 
                        <list-item><p>List Item 2</p></list-item> 
                        <list-item><p>List Item 3</p></list-item> 
                        </list> 
                    </p> 
                </sec> 
            </body> 
        </book-part> 
    </book-body> 
</book> 

在这个例子中,我需要标签内的所有内容(最好没有标题,但稍后我会弄清楚)。 我曾尝试使用“xml.etree.ElementTree”和“minidom”但没有成功。

这是我使用 minidom 的代码示例

from xml.dom import minidom 
 
xmldoc = minidom.parse("xCHES.xml") 
 
book = xmldoc.getElementsByTagName("book")[0] 
 
sec = book.getElementsByTagName("sec") 

当我列出一些元素时,我得到的数字与我在 xml 文件中搜索“<sec”时得到的数字相同,所以我想我得到了所有元素。 在这一点之后我被卡住了,我找不到如何将所有内容提取为文本的方法。

“ElementTree”也是一样,我可以找到所有 <sec>元素,但我无法提取文本,或者只能提取其中的一小部分。

所以如果有人能帮我解决这个问题,那就太好了。什么方法都无所谓,只要能完成工作即可。

编辑: 期望的输出将是

<title>Introduction</title> 
<p>This is a <em>paragraph</em></p> 
<p>This is second paragraph 
    <list list-type="bullet"> 
    <list-item><p>List Item 1</p></list-item> 
    <list-item><p>List Item 2</p></list-item> 
    <list-item><p>List Item 3</p></list-item> 
    </list> 
</p> 

但作为刺痛。这可以在一行中,格式无关紧要。

谢谢你:)

请您参考如下方法:

关注@stovfl 在 How to get inner content as string using minidom from xml.dom? 上的回答

也许这对你有用?

def getText(nodelist): 
    # Iterate all Nodes aggregate TEXT_NODE 
    rc = [] 
    for node in nodelist: 
        if node.nodeType == node.TEXT_NODE: 
            rc.append(node.data) 
        else: 
            # Recursive 
            rc.append(getText(node.childNodes)) 
    return ''.join(rc) 
 
 
# Iterate <sec..>...</sec> Node List 
for node in nodelist: 
    print(getText(node.childNodes)) 

输出:

                Introduction 
                This is a paragraph 
                This is second paragraph 
 
                    List Item 1 
                    List Item 2 
                    List Item 3