簡體   English   中英

在另一個 XML 中包含一個 XML 並用 python 解析它

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

我想在另一個 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

它打印根的所有子元素的標簽

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 文件包含在另一個文件中,我很困惑如何編寫架構。 我該如何解決?

以下

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

This is a paragraph.

不知道為什么要使用 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