正在解析 Python 中没有 'root' 节点的 XML 文件

Parsing XML files that do not have 'root' node in Python

我的客户希望我解析超过 100,00 个 xml 文件并将它们转换为文本文件。

我已经成功解析了几个文件并将它们转换为文本文件。但是我设法通过编辑 xml 并在 xml 文件中添加 <root></root> 来做到这一点。

这似乎效率低下,因为我必须编辑近 100,00 个 xml 文件才能达到我想要的结果。

我的 python 代码是否可以识别第一个节点并将其作为根节点读取?

我试过使用Python XML Parsing without root中显示的方法 ,但是我不完全理解它,我不知道在哪里实现它。

XML格式如下:

<Thread>
   <ThreadID></ThreadID>
   <Title></Title>
   <InitPost>
        <UserID></UserID>
        <Date></Date>
        <icontent></icontent>
  </InitPost>
  <Post>
       <UserID></UserID>
       <Date></Date>
       <rcontent></rcontent>
  </Post>
</Thread>

这是我关于如何解析 XML 文件的代码:

import os
from xml.etree import ElementTree


saveFile = open('test3.txt','w')

for path, dirs, files in os.walk("data/sample"):
   for f in files:
    fileName = os.path.join(path, f)
    with open(fileName, "r", encoding="utf8") as myFile:
        dom = ElementTree.parse(myFile)

        thread = dom.findall('Thread')

        for t in thread:

            threadID = str(t.find('ThreadID').text)
            threadID = threadID.strip()

            title = str(t.find('Title').text)
            title = title.strip()

            userID = str(t.find('InitPost/UserID').text)
            userID = userID.strip()

            date = str(t.find('InitPost/Date').text)
            date = date.strip()

            initPost = str(t.find('InitPost/icontent').text)
            initPost = initPost.strip()

        post = dom.findall('Thread/Post')

其余代码只是写入输出文本文件。

我不知道 Python 解析器是否支持 DTD,但如果支持,那么一种方法是像这样定义一个简单的包装文档

<!DOCTYPE root [
<!ENTITY e SYSTEM "realdata.xml">
]>
<root>&e;</root>

并将解析器指向此包装文档而不是 realdata.xml

不确定 Python,但一般来说,无论是在文档元素(根)级别还是在其他地方,您都可以使用 SGML 推断缺失的标签。基本技术是创建一个 DTD 来像这样声明文档元素

<!DOCTYPE root [
  <!ELEMENT root O O ANY>
]>
<!-- your document character data goes here -->

重要的是 O O(字母 O)标记省略指示符告诉 SGML root 的开始和结束元素标记都可以省略。

另请参阅以下问题以获取更多详细信息:

  • Querying Non-XML compliant structured data
  • Adding missing XML closing tags in Javascript

将 xml 作为文本加载并用根元素将其包裹。

'1.xml' 是您发布的xml

from xml.etree import ElementTree as ET

files = ['1.xml'] # your list of files goes here
for file in files:
    with open(file) as f:
        # wrap it with <r>
        xml = '<r>' + f.read() + '</r>'
        root = ET.fromstring(xml)
        print('Now we are ready to work with the xml')