[嗨,我想在我的python代码中解析2个xml文件。并想使用config.xml中的标签值替换strings.xml中的标签值。由于我是python的新手,所以我没有任何线索。
这是我的代码:
**import os
import xml.etree.ElementTree as ET
root= ET.parse("C:/Users/Desktop/B-C-
Final/BuildConfig/Droid/Resources/values/Strings.xml")
search = root.findall(".//string/.[@name='app_name']")
print(search[0].text)
src= ET.parse("C:\\Users\\Desktop\\B-C-Final\\BuildConfig\\BuildConfig\\Config.xml")
appname = src.findall(".//string/.[@name='app_name']")
search[0].text = search[0].text.replace('search[0].text','appname[0].text')**
但是我遇到了类似的错误:
**Traceback (most recent call last):
File "c:/Users/Desktop/Pythoncode/hello.py", line 9, in <module>
src= ET.parse("C:\\Users\\Desktop\\B-C-Final\\BuildConfig\\BuildConfig\\Config.xml")
File "C:\Users\Desktop\Python\lib\xml\etree\ElementTree.py", line 1202, in parse
tree.parse(source, parser)
File "C:\Users\Desktop\Python\lib\xml\etree\ElementTree.py", line 595, in parse
self._root = parser._parse_whole(source)
xml.etree.ElementTree.ParseError: not well-formed (invalid token): line 11, column 16**
这是配置文件:
?xml version="1.0" encoding="UTF-8" ?>
<configuration>
<appSettings>
<add key="K0" value="0" />
<add key="K1" value="1" />
<add key="K2" value="2" />
</appSettings>
<uses-sdk android:minSdkVersion="18" />
<application android:label="Build" android:icon = "@hello/icon">
</application>
<string name="app_name">abc</string>
</configuration>
尝试一下。
from simplified_scrapy import SimplifiedDoc,req,utils
html = utils.getFileContent("config.xml")
doc = SimplifiedDoc(html)
app_name = doc.select('string@name=app_name').text
html1 = utils.getFileContent("Strings.xml")
doc1 = SimplifiedDoc(html1)
app_name1 = doc1.select('string@name=app_name')
app_name1.setContent(app_name)
print (app_name1.outerHtml)
utils.saveFile("Strings.xml",doc1.html)
结果:
<string name="app_name">abc</string>
这里有更多示例。 https://github.com/yiyedata/simplified-scrapy-demo/blob/master/doc_examples