zoukankan      html  css  js  c++  java
  • python 修改xml文件

    在百度知道里面有人问了这么一个问题:

    有一个xml文件:
    <root>text
    <a/>
    <a/>
    ...这里省略n个<a/>

    <root>
    想替换成下面的形式:
    <root>text
    <a1>a1 for a</a1>
    <a2>a2 for a</a2>
    ...n个<an>...</an>

    <root>
    请问,应该怎么替换呢?用字符串替换或lxml包的方法都可以。谢谢!

    我给出了两种答案,一种是用字符串替换,一种是xml解析。如下

    字符串替换:

     1 old=open("test.xml")
     2 lines=old.readlines()
     3 a="<a/>"
     4 i=1
     5 newlines=[]
     6 for line in lines:
     7     if a in line:
     8         line=line.replace(a,"<a"+str(i)+">a"+str(i)+"for a</a"+str(i)+">")
     9         i=i+1
    10     newlines.append(line)
    11 
    12 for line in newlines:
    13     print line
    14 
    15 new=open("newtest.xml","w")
    16 new.writelines(newlines)
    17 new.close()
    18 old.close()

      xml解析:

     1 import xml.dom.minidom
     2 oldxmlfile=open("test.xml")
     3 oldxml=oldxmlfile.read()
     4 oldxmlfile.close()
     5 doc = xml.dom.minidom.parseString(oldxml)
     6 index=1
     7 for node in doc.getElementsByTagName("a"):
     8     node.tagName="a"+str(index)
     9     index=index+1
    10 newxml=doc.toprettyxml()
    11 xmlfile=open("newxml2.xml","w")
    12 xmlfile.write(newxml);
    13 xmlfile.close()
  • 相关阅读:
    java中继承和多态的理解
    汽车租赁系统
    s2第六章继承和多态
    第三章泛型集合ArrayList 和Hashtable
    第二章项目总结
    s2第二章深入c#类型
    .NET平台
    航班查询系统
    java初始重点语法
    JDBC
  • 原文地址:https://www.cnblogs.com/njuxdj/p/python_modify_xml.html
Copyright © 2011-2022 走看看