我需要搜索元素并替换为XML文件中的另一个值。只能在条件匹配行进行更换。你知道吗
我有以下xml文件。你知道吗
<?xml vn="1.0" encoding="UTF-8"?>
<proj>
<mV>4.0.0</mV>
<gId>com.test</gId>
<aId>console</aId>
<vn>1.0</vn>
<bld>
<plugins>
<plugin>
<gId>org.apache.maven.plugins</gId>
<aId>maven-compiler-plugin</aId>
<vn>1.1</vn>
<configuration>
<source>1.0</source>
<target>1.0</target>
<showWarnings>true</showWarnings>
</configuration>
</plugin>
</plugins>
</bld>
<dps>
<dp>
<gId>org.sk</gId>
<aId>sk-api</aId>
<vn>1.7.20</vn>
</dp>
<dp>
<gId>org.sk</gId>
<aId>sk-log</aId>
<vn>1.7.25</vn>
</dp>
</dps>
</proj>
以下是更换代码。你知道吗
aIdValue = "sk-log"
tree = ET.parse('test.xml')
al_rt = tree.getal_rt()
dp = al_rt.findall(".//xmlns:dp")
for d in dp:
aId = d.find("xmlns:aId")
vn = d.find("xmlns:vn")
if aIdValue == aId.text:
print aId.text
print vn.text
vn.text = vn.text
tree.write('test.xml')
这里我从print语句得到的值是aId.text
是sk-log
和vn.text
是1.7.25
。我只需要在那一行中用somevalue
替换1.7.25
。上面的代码对我不起作用。我该怎么做?你知道吗
预期输出为
<?xml vn="1.0" encoding="UTF-8"?>
<proj>
<mV>4.0.0</mV>
<gId>com.test</gId>
<aId>console</aId>
<vn>1.0</vn>
<bld>
<plugins>
<plugin>
<gId>org.apache.maven.plugins</gId>
<aId>maven-compiler-plugin</aId>
<vn>1.1</vn>
<configuration>
<source>1.0</source>
<target>1.0</target>
<showWarnings>true</showWarnings>
</configuration>
</plugin>
</plugins>
</bld>
<dps>
<dp>
<gId>org.sk</gId>
<aId>sk-api</aId>
<vn>1.7.20</vn>
</dp>
<dp>
<gId>org.sk</gId>
<aId>sk-log</aId>
<vn>somevalue</vn>
</dp>
</dps>
</proj>
以下是您需要的: 导入xml.etree.ElementTree文件作为ET
使用
BeautifulSoup
和find_next()
:列表_文本.xml地址:
然后:
输出:
编辑:
要将其写入同一个xml文件,我们将使用
soup.prettify()
:输出:
您是否尝试使用模块xmltodict将该xml更改为dict,然后再次将其更改为xml?你知道吗
Here is a little guide。你知道吗
And here the repository。你知道吗
这里有一个小函数来替换dict上的元素,当两个键相等时它会有问题,但是对于用不重复的键替换元素,它是可以的,至少对我来说是有效的:
我制作了这个程序并完成了以下工作:
敬礼
相关问题 更多 >
编程相关推荐