Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/299.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中解析XML真的这么难看吗?_Python_Minidom - Fatal编程技术网

在python中解析XML真的这么难看吗?

在python中解析XML真的这么难看吗?,python,minidom,Python,Minidom,我有一个非常小的XML文件(22行),有5个元素(?),我只想要其中的一个值 这是在不使用正则表达式的情况下获取已找到值的唯一方法 from xml.dom.minidom import parse float(parse(filePath).getElementsByTagName('InfoType')[0].getElementsByTagName('SpecificInfo')[0].firstChild.data) 我觉得我错过了什么。必须有一种更为Python的方式来处理XML,对

我有一个非常小的XML文件(22行),有5个元素(?),我只想要其中的一个值

这是在不使用正则表达式的情况下获取已找到值的唯一方法

from xml.dom.minidom import parse
float(parse(filePath).getElementsByTagName('InfoType')[0].getElementsByTagName('SpecificInfo')[0].firstChild.data)

我觉得我错过了什么。必须有一种更为Python的方式来处理XML,对吗?

至少可以使用pyQuery:(Python中的jQuery语法)而不是那些冗长的DOM浏览函数使用elementtree是从XML中获取单个值的更为Python的方式:

它是最新Python版本的标准库的一部分。

该库比xml.dom.minidom更具Python风格。如果我正确理解了您的XML结构,那么使用ElementTree时,您的代码将如下所示:

import xml.etree.ElementTree as ET
tree = ET.parse(filePath)
data = float(tree.find('InfoType/SpecificInfo')[0].text)

这应该比您目前正在做的要干净得多。

我认为,现在就因为MinidomAPI不具备音速而放弃它还为时过早。通过几个助手函数,我们可以得到我们想要的pythonic,例如:

# Helper function to wrap the DOM element/attribute creation API.
def El( tag, attribs = None, text = None ):
    el = doc.createElement( tag )
    if text: el.appendChild( doc.createTextNode( text ))
    if attribs is None: return el
    for k, v in attribs.iteritems(): el.setAttribute( k, v )
    return el

# Construct an element tree from the passed tree.
def make_els( parent_el, this_el, child_els ):
    parent_el.appendChild( this_el )
    for x in child_els:
        if type( x ) is tuple:
            child_el, grandchild_els = x
            make_els( this_el, child_el, grandchild_els )
        else:
            this_el.appendChild( x )

doc.removeChild( doc.documentElement )
make_els( doc, El( 'html', { 'xmlns': 'http://www.w3.org/1999/xhtml', 'dir': 'ltr', 'lang': 'en' }), [
    (   El( 'head' ), [
        El( 'meta', { 'http-equiv': 'Content-Type', 'content': 'text/html; charset=utf-8' }),
        El( 'meta', { 'http-equiv': 'Content-Style-Type', 'content': 'text/css' }),
        El( 'link', { 'rel': 'stylesheet', 'type': 'text/css', 'href': 'main.css', 'title': 'Default Stylesheet' }),
        El( 'title', {}, 'XXXX XXXX XXXXr {}, {}'.format( args.xxxx, env.build_time ))
    ]),
    (   El( 'frameset', { 'cols': '20%, 80%' }), [
        El( 'frame', { 'src': 'xxx_list.html', 'name': 'listframe', 'title': 'XXXX XXXX XXXX' }),
        El( 'frame', { 'src': 'xxx_all_xxxx_all.html', 'name': 'regframe', 'title': 'XXX XXXX XXXX' }),
        (   El( 'noframes' ), [
            (   El( 'body' ), [
                El( 'h2', {}, 'Frame Alert' ),
                El( 'p', {}, 'This document is designed to be viewed using the frames feature.' )
            ])
        ])
    ])
])
print '\ndoc:\n', doc.toprettyxml( indent = '  ' )

我建议用谷歌搜索XPath。顺便说一句:你不能用正则表达式解析XML(或HTML或大多数标记语言)。后者是类型3(常规),前者不是。