【问题标题】:Unable to parse XML file with python.Want to remove a line from python file for it .Help me to remove the line无法使用 python 解析 XML 文件。想从 python 文件中删除一行。帮我删除该行
【发布时间】:2013-06-03 17:22:08
【问题描述】:

您好,我正在使用 etree 来解析 xml 文件。我在解析 xml 文件时遇到问题。以下是详细信息。

<niktoscan .................................... >#don't want to remove this line
<scandetails>
data 
</scandetials>
<niktoscan ....................................> #line 1 to remove
<scandetails>
data
</scandetials>
 <niktoscan ....................................> #line 2 to remove
<scandetails>
data
</scandetials>
</niktoscan>

正如您在上面的代码中看到的,niktoscan 再次出现而没有结束标记。我想要的是删除开始和结束之间的 niktoscans 行,只留下第一个 niktoscan 标记。 我很困惑如何删除 niktoscan 线。用python帮我解决这个问题。

【问题讨论】:

  • 抱歉我没明白你能用代码演示它吗??
  • 您的输入似乎不是格式正确的 xml(缺少一些关闭标签)。 etree.parse(input_file) 会产生什么错误? xml 不是面向行的(尽管某些 xml 解析器可以保留空格)。您是要递归删除 niktoscan 元素及其子元素还是仅删除 niktoscan 元素本身?
  • @J.F.Sebastian 我想删除第二个和第三个 nicktoscan 标签,而不是他们的孩子,这将达到我的目的.....希望找到好的解决方案。

标签: python python-2.7 python-3.x xml-parsing


【解决方案1】:

您可以使用它来解析您的文件:

with open('niktoscan.txt') as f:
    content = f.readlines()

foundone = False
print type(content)

cleanedContent = []
for line in content:
    print line

    foundnik = line.find('<niktoscan')
    if not (foundnik != -1 and foundone):
        cleanedContent.append(line)

    if foundnik != -1:
        foundone = True
print "\n\n ########### cleaned content ########### \n\n"

for line in cleanedContent:
    print line

然后您可以将结果放入您的解析器。

【讨论】:

    猜你喜欢
    • 2014-12-14
    • 2023-02-08
    • 1970-01-01
    • 1970-01-01
    • 2015-10-08
    • 2021-08-10
    • 1970-01-01
    • 2018-09-21
    • 1970-01-01
    相关资源
    最近更新 更多