【问题标题】:Parsing XML tags through Python and replace it using xml.dom.minidom通过 Python 解析 XML 标签并使用 xml.dom.minidom 替换它
【发布时间】:2013-02-15 18:28:19
【问题描述】:

我的 XML 文件 test.xml 包含以下标签

<?xml version="1.0" encoding="ISO-8859-1"?>
<AppName>
    <out>This is a sample output with <test>default</test> text </out>
<AppName>

到目前为止,我已经编写了一个 python 代码,它执行以下操作:

from xml.dom.minidom import parseString
list = {'test':'example'}
file = open('test.xml','r')
data = file.read()
file.close()
dom = parseString(data)
if (len(dom.getElementsByTagName('out'))!=0):
    xmlTag = dom.getElementsByTagName('out')[0].toxml()
    out = xmlTag.replace('<out>','').replace('</out>','')
    print out

下面程序的输出是This is a sample output with &lt;test&gt;default&lt;/test&gt; text

您还会注意到我有一个定义了list = {'test':'example'} 的列表。

我想检查out里是否有一个标签列在列表中,将替换为相应的值,否则为默认值。

在这种情况下,输出应该是:

This is a sample output with example text

【问题讨论】:

    标签: python xml xml-parsing


    【解决方案1】:

    这或多或少会做你想要的:

    from xml.dom.minidom import parseString, getDOMImplementation
    
    test_xml = '''<?xml version="1.0" encoding="ISO-8859-1"?>
    <AppName>
        <out>This is a sample output with <test>default</test> text </out>
    </AppName>'''
    
    replacements = {'test':'example'}
    dom = parseString(test_xml)
    if (len(dom.getElementsByTagName('out'))!=0):
        xmlTag = dom.getElementsByTagName('out')[0]
        children =  xmlTag.childNodes
        text = ""
        for c in children:
            if c.nodeType == c.TEXT_NODE:
                text += c.data
            else:
                if c.nodeName in replacements.keys():
                    text += replacements[c.nodeName]
                else: # not text, nor a listed tag
                    text += c.toxml()
        print text
    

    请注意,我使用了replacements 而不是list。在 python 术语中,它是一个字典,而不是一个列表,所以这是一个令人困惑的名字。它也是一个内置函数,因此您应该避免将其用作名称。

    如果您想要一个 dom 对象而不仅仅是文本,则需要采用不同的方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-22
      • 1970-01-01
      • 2015-01-03
      • 2020-05-04
      • 2012-08-17
      • 2016-01-11
      • 2017-10-13
      • 1970-01-01
      相关资源
      最近更新 更多