【发布时间】:2019-07-13 20:01:45
【问题描述】:
我需要在 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')
所以在这里我从打印语句中得到的值是 aId.text 是 sk-log 和 vn.text 是 1.7.25。我只需要在该特定行中将1.7.25 替换为somevalue。上面的代码对我不起作用。我该怎么做?
预期的输出将是
<?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>
【问题讨论】:
-
这一行看起来很可疑:“vn.text = vn.text”。显然,这没有任何作用。你的意思是其他东西会真正改变文本吗?也许“vn.text = 'somevalue'”?
-
vn.text = vn.text- 你可以忽略这个。我刚刚在调试时放了这个。 @joe 管理员 -
是的.. 我会用预期的输出更新问题
-
@moong mu 回答有帮助吗?如果是,您可以将其标记为接受。欢呼
-
我将其标记为已接受