在另一个XML中包含一个XML并使用python对其进行解析 [英] Include one XML within another XML and parse it with python

查看:80
本文介绍了在另一个XML中包含一个XML并使用python对其进行解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在另一个XML文件中包含一个XML文件,并用python解析它.我正在尝试通过Xinclude实现它.有一个file1.xml看起来像

I wanted to include an XML file in another XML file and parse it with python. I am trying to achieve it through Xinclude. There is a file1.xml which looks like

<?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看起来像

and file2.xml which looks like

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

现在在我的python代码中,我尝试像这样访问它:

Now in my python code i tried to access it like:

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

它说根没有子名为test或document的子代.那我该如何访问file2.xml中的内容?

It says the root doesnt have children named test or document. Then how am i suppose to access the content in file2.xml?

我知道我可以使用以下模式从python访问XML元素:

I know that I can access the XML elements from python with schema like:

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

但是由于这里一个XML文件包含在另一个文件中,所以我对如何编写模式感到困惑.我该怎么解决?

But since here one XML file is included in another, I am confused how to write the schema. How can i solve it?

推荐答案

下方

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)

输出

This is a paragraph.

这篇关于在另一个XML中包含一个XML并使用python对其进行解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆