Skip to main content
 首页 » 编程设计

python之如何解析具有多个根元素的xml

2025年05月04日12zengkefu

我需要解析 var 和 group 根元素。

代码

import xml.etree.ElementTree as ET 
tree_ownCloud = ET.parse('0020-syslog_rules.xml') 
root = tree_ownCloud.getroot() 

错误

xml.etree.ElementTree.ParseError: junk after document element: line 17, column 0

示例 XML

<var name="BAD_WORDS">core_dumped|failure|error|attack| bad |illegal |denied|refused|unauthorized|fatal|failed|Segmentation Fault|Corrupted</var> 
 
<group name="syslog,errors,"> 
  <rule id="1001" level="2"> 
    <match>^Couldn't open /etc/securetty</match> 
    <description>File missing. Root access unrestricted.</description> 
    <group>pci_dss_10.2.4,gpg13_4.1,</group> 
  </rule> 
 
  <rule id="1002" level="2"> 
    <match>$BAD_WORDS</match> 
    <options>alert_by_email</options> 
    <description>Unknown problem somewhere in the system.</description> 
    <group>gpg13_4.3,</group> 
  </rule> 
</group> 

我尝试在 stackoverflow 上关注其他几个问题 here , 但没有任何帮助。

我知道原因,由于它没有被解析,人们通常会尝试破解。 IMO 在 XML 中有多个根元素是一个非常常见的用例,ET 解析库中必须有一些东西才能完成这项工作。

请您参考如下方法:

如评论中所述,一个 XML 文件不能有多个根。就这么简单。

如果您确实以这种格式接收/存储数据(那么它就不是正确的 XML)。你可以考虑用假标签围绕你所拥有的东西,例如

import xml.etree.ElementTree as ET 
 
with open("0020-syslog_rules.xml", "r") as inputFile:  
  fileContent = inputFile.read() 
  root = ET.fromstring("<fake>" + fileContent +"</fake>") 
  print(root)