python - 覆盖 XML 文件

标签 python xml parsing elementtree

我正在尝试使用 elementtree 解析 XML 文件。然而,我试图读取的 XML 文件是从 MySql 导出的,当创建 XML 文件时,如果我在数据库中有一个条目,如:c:cygwin\bin ,它会将 '\b' 转换为退格键。无论如何,我试图从 XML 文件中删除 '\b' 的所有条目,以便我可以通过 elementtree.parse() 方法发送它。由于某种原因,在删除 '\b' 的所有条目后,我没有写出整个文件。

这就是我正在做的事情:

def preprocess(file):
    #exporting from MySQL query browser adds a weird
    #character to the result set, remove it
    #so the XML parser can read the data
    print "in preprocess"
    lines = map(lambda line: line.replace("\b", " "), file)

    #go to the beginning of the file
    file.seek(0);

    #overwrite with correct data
    file.writelines(lines)
    sys.exit()


'''Entry into the program'''
#test the file to see if processing is needed before parsing
for line in xml_file:
    p = re.compile("\\b") #search for '\b'
    if(p.match(line)):
        processing = True
        break #only one match needed

if processing:
    preprocess(xml_file)

结果是我最终得到一个 header 被切断的 XML 文件,因此当传递到解析器时它会失败。

这是从 XML 文件中删除的内容:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE ROOT SYSTEM "diskreport.dtd">
<ROOT>
    <row>
      <field name="buildid">26960</field>
      <field name="cast(status as char)">Filesystem           1K-blocks      Used Available Use% Mounted on
C:cygwinin        285217976  88055920 197162056  31% /usr/bin

任何帮助/想法都会很棒, 谢谢

最佳答案

我发现了问题,当我确实需要使用 p.search 时,我使用 p.match 来查找 '\b' 的匹配项,p.match 只从行首查找,search 查找发生在整个生产线上。

解决方案:

def preprocess(file):
    #exporting from MySQL query browser adds a weird
    #character to the result set, remove it
    #so the XML parser can read the data
    print "in preprocess"
    lines = map(lambda line: line.replace("\b", ""), file)

    #go to the beginning of the file
    file.seek(0);

    #overwrite with correct data
    file.writelines(lines)
    sys.exit()


'''Entry into the program'''
#test the file to see if processing is needed before parsing
for line in xml_file:
    p = re.compile("\\b")
    if(p.search(line)): ####Changed to p.search here
        processing = True
        break #only one match needed

if processing:
    preprocess(xml_file)

关于python - 覆盖 XML 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6347019/

相关文章:

java - Log4j2 未记录到文件

java - 仅包含 hibernate.properties 文件的 Hibernate 配置。没有任何 hibernate.cfg.xml

c# - 将在线 XML 文件中的条目写入隔离存储

java - ANTLR4 在较长的文件上抛出 java.lang.StackOverflowError

c++ - linux守护进程的结构

javascript - 正则表达式匹配括号之间的 Javascript 函数中的参数

python - 在Python中访问多个对象中的字典时出现问题

javascript - 如何使用 FastAPI 为跨源请求设置 cookie

python - 如何在pytest下测试单个文件

python - matplotlib 中标签的正确对齐