简体   繁体   English

在另一个 XML 中包含一个 XML 并用 python 解析它

[英]Include one XML within another XML and parse it with python

I wanted to include an XML file in another XML file and parse it with python.我想在另一个 XML 文件中包含一个 XML 文件,并用 python 解析它。 I am trying to achieve it through Xinclude.我正在尝试通过 Xinclude 来实现它。 There is a file1.xml which looks like有一个 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>

and file2.xml which looks like和 file2.xml 看起来像

<para>This is a paragraph.</para>

Now in my python code i tried to access it like:现在在我的 python 代码中,我尝试像这样访问它:

from xml.etree import ElementTree, ElementInclude

tree = ElementTree.parse("file1.xml")
root = tree.getroot()
for child in root.getchildren():
    print child.tag

It prints the tag of all child elements of root它打印根的所有子元素的标签

document
test

Now when i tries to print the child objects directly like现在,当我尝试直接打印子对象时

print root.document
print root.test

It says the root doesnt have children named test or document.它说根没有名为 test 或 document 的子级。 Then how am i suppose to access the content in file2.xml?那么我想如何访问 file2.xml 中的内容?

I know that I can access the XML elements from python with schema like:我知道我可以使用如下架构从 python 访问 XML 元素:

    schema=etree.XMLSchema(objectify.fromstring(configSchema))
    xmlParser = objectify.makeparser(schema = schema)
    cfg = objectify.fromstring(xmlContents, xmlParser)
    print cfg.elemetName # access element

But since here one XML file is included in another, I am confused how to write the schema.但是由于这里一个 XML 文件包含在另一个文件中,我很困惑如何编写架构。 How can i solve it?我该如何解决?

Below以下

import xml.etree.ElementTree as ET


xml1 = '''<?xml version="1.0"?>
<root>
  <test>some text</test>
</root>'''

xml2 = '''<para>This is a paragraph.</para>'''

root1 = ET.fromstring(xml1)
root2 = ET.fromstring(xml2)

root1.insert(0,root2)

para_value = root1.find('.//para').text
print(para_value)

output output

This is a paragraph.

Not sure why you want to use XInclude, but including an XML file in another one is a basic mechanism of SGML and XML, and can be achieved without XInclude as simple as:不知道为什么要使用 XInclude,但在另一个文件中包含 XML 文件是 SGML 和 XML 的基本机制,并且可以在没有 XInclude 的情况下实现,如下所示:

<!DOCTYPE root [
  <!ENTITY externaldoc SYSTEM "file2.xml">
]>
<root>
  <document>
    &externaldoc;
  </document>
  <test>some text</test>
</root>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM