【问题标题】:Overwriting XML file覆盖 XML 文件
【发布时间】:2011-06-14 16:43:55
【问题描述】:

我正在尝试使用 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)

结果是我最终得到了一个标头被截断的 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

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

【问题讨论】:

  • 为什么不用\\ 替换每个\ ?这样,您就不会遇到其他转义序列的问题(例如,当路径包含 \t\n 等时。
  • 我导出 XML 文件的数据库中的数据是由在此处的服务器上运行的许多脚本生成的,更改它们输出的数据不是一个可行的选择
  • 他的意思是,不是用" "代替'\b',而是用'\\'代替'\'
  • 我只能对从 MySql 导出的 XML 文件进行替换操作。导出后没有'\'转换成'\\',只有'\b'字符嵌入在XML文件中

标签: python xml parsing elementtree


【解决方案1】:

我发现了问题,当我真的需要使用 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)

【讨论】:

  • 注意:您可以接受自己的答案,如果它正确且有效
猜你喜欢
  • 2011-06-24
  • 2021-04-06
  • 1970-01-01
  • 2023-02-07
  • 2018-06-10
  • 2013-11-27
  • 2012-05-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多