我有两个xml文件。我需要在一个特定的标签之后将一个xml文件的内容添加到另一个说file2.xml中。例如file1.xml。
file1.xml
<server>
<id>6</id>
<host_name>abd</host_name>
</server>
<server>
<id>7</id>
<host_name>abc</host_name>
</server>
file2.xml
<serverList>
<server>
<id>10</id>
<host_name>bhgd</host_name>
</server>
<server>
<id>19</id>
<host_name>mngvd</host_name>
</server>
</serverList>
我需要在标记</serverList>
预期结果:
<serverList>
<server>
<id>10</id>
<host_name>bhgd</host_name>
</server>
<server>
<id>19</id>
<host_name>mngvd</host_name>
</server>
<server>
<id>6</id>
<host_name>abd</host_name>
</server>
<server>
<id>7</id>
<host_name>abc</host_name>
</server>
</serverList>
答案 0 :(得分:1)
我假设您没有代码(最好使用xml解析器,但如果不这样做):
with open("file1.xml", "r") as f1:
lines1 = f1.readlines()
with open("file2.xml","r") as f2:
lines2 = f2.readlines()
with open("file3.xml","a") as f3:
for line in lines2:
if line == "</serverList>"
f3.write(lines1+"\n")
f3.write(line+"\n")
else:
f3.write(line+"\n")
import subprocess
subprocess.call(["mv file3.xml file2.xml"],shell=True)
答案 1 :(得分:0)
最好的方法是始终使用xml解析器。 Dom4j非常好看。对于这段代码,您需要dom4j和jaxen jar或maven依赖。
Document xml1 = new SAXReader().read(new File("file1.xml"));
Document xml2 = new SAXReader().read(new File("file2.xml"));
List<Element> servers = (List<Element>) xml1.selectNodes("//*/server");
for(Element server : servers)
xml2.getRootElement().addElement(server);
然后将xml2保存到文件中