我想将一个 XML 文件包含在另一个 XML 文件中并用 python 解析它。我正在尝试通过 Xinclude 来实现它。有一个 file1.xml 看起来像
<?xml version="1.0"?>
<root>
<document xmlns:xi="http://www.w3.org/2001/XInclude">
<xi:include href="file2.xml" parse="xml" />
</document>
<test>some text</test>
</root>
和 file2.xml 看起来像
<para>This is a paragraph.</para>
现在在我的 python 代码中我尝试像这样访问它:
from xml.etree import ElementTree, ElementInclude
tree = ElementTree.parse("file1.xml")
root = tree.getroot()
for child in root.getchildren():
print child.tag
它打印 root 的所有子元素的标签
document
test
现在,当我尝试直接打印子对象时
print root.document
print root.test
它说根没有名为 test 或 document 的子项。那么我该如何访问 file2.xml 中的内容呢?
我知道我可以使用如下模式从 python 访问 XML 元素:
schema=etree.XMLSchema(objectify.fromstring(configSchema))
xmlParser = objectify.makeparser(schema = schema)
cfg = objectify.fromstring(xmlContents, xmlParser)
print cfg.elemetName # access element
但由于这里一个 XML 文件包含在另一个文件中,所以我很困惑如何编写架构。我该如何解决它?