簡體   English   中英

在 Python 中解析 XML 但忽略實體

[英]Parse XML in Python but ignoring entity

我必須傳遞一個 XML 文件並將數據存儲到數據庫中。 問題是這個 XML 有一些我不想導入的實體,但相反,我想要原始實體標簽。 為了更好地澄清,我有以下架構:

<!ENTITY exa "example">
.....
<mytag>&exa;</mytag>

如果我嘗試使用以下代碼解析上面讀取標簽“mytag”的代碼:

import xml.etree.ElementTree as ET

tree = ET.parse(xmlfile)
root = tree.getroot()

for item in root:
        if item.tag == "mytag":

我讀了字符串“example”。 相反,我想要標簽“exa”。 我想是可能的,但因為我是新的 t python delelompent 我找不到正確的方法來獲得這個結果。 一些建議? 謝謝

下面是一個開始的例子:

import os
import re
from lxml import etree

xmlfile = 'testfile.xml'
xml_path = '%s/%s' % (os.path.dirname(os.path.realpath(__file__)), xmlfile)

parser = etree.XMLParser(resolve_entities=False)
tree = etree.parse(xml_path, parser)
# root = tree.getroot()

root = tree.xpath('/mytag')

for item in root:
    entity = etree.tostring(item, pretty_print=True).decode('utf-8')
    print('ENTITY     : ', entity)
    entity_value = re.findall(r'&(.*?);', entity)
    print('Parsed str : ', entity_value)

但是可能有一種更簡單的方法來恢復該值。

您可以修改 xml 文件中的每個ENTITY標記,以便它們具有您想要的值,然后在最后將它們修改回來。

您可以創建一個類來克隆您的 xml 文件:

import os
import re

class NoEntities:
    """
    Creates a clone of the target xml file such that the <!ENTITY x "y"> tags
    become <!ENTITY x "x">.
    """

    def __init__(self, xmlFile):
        self.targetName = xmlFile
        self.tmpName = 'temp.xml'

    def __enter__(self):
        match = r'<!ENTITY\s+(\S+)\s+"[^"]+"\s*>'
        replace = r'<!ENTITY \1 "\1">'

        with open(self.targetName) as target:
            with open(self.tmpName, 'w') as tmp:
                tmp.writelines(
                    re.sub(match, replace, line)
                    for line in target
                )

        return self.tmpName

    def __exit__(self, *exec_info):
        os.remove(self.tmpName)

然后在 with 塊中使用它:

import xml.etree.ElementTree as ET

with NoEntities(pathToOriginalXml) as noEntityXml:
    tree = ET.parse(noEntityXml)
    # Do what you like...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM