<p>使用<code>BeautifulSoup</code>和<code>find_next()</code>:</p>
<p>列表_文本.xml地址:</p>
<pre><code><?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>
</code></pre>
<p>然后:</p>
<pre><code>from bs4 import BeautifulSoup
with open('list_test.xml','r') as f:
soup = BeautifulSoup(f.read(), "html.parser")
aid = soup.find_all('aid')
for s in aid:
if s.text == 'sk-log':
vn = s.find_next('vn')
print("Original Value: {}".format(vn.text))
vn.string = 'SomeValue'
print("Replaced value: {}".format(vn.text))
</code></pre>
<p>输出:</p>
<pre><code>Original Value: 1.7.25
Replaced value: SomeValue
</code></pre>
<p><strong>编辑:</strong></p>
<p>要将其写入同一个xml文件,我们将使用<code>soup.prettify()</code>:</p>
<pre><code>from bs4 import BeautifulSoup
with open('list_test.xml','r') as f:
soup = BeautifulSoup(f.read(), features="lxml")
aid = soup.find_all('aid')
for s in aid:
if s.text == 'sk-log':
vn = s.find_next('vn')
print("Original Value: {}".format(vn.text))
vn.string = 'SomeValue'
print("Replaced value: {}".format(vn.text))
with open("list_test.xml", "w") as f_write:
f_write.write(soup.prettify())
</code></pre>
<p>输出:</p>
<pre><code><?xml vn="1.0" encoding="UTF-8"?>
<html>
<body>
<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>
</body>
</html>
</code></pre>