【问题标题】:How to parse more than one xml file in python code?如何在 python 代码中解析多个 xml 文件?
【发布时间】:2020-08-04 06:05:28
【问题描述】:

嗨,我想在我的 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>

【问题讨论】:

  • 您想在这里获取变量的值吗? '搜索[0].text','appname[0].text'
  • 是的,我希望将这些值复制到我的 string.xml 中。例如。从 config.xml 中获取 app_name 的值并替换 string.xml 文件中的 app_name 值。

标签: python android python-3.x xml xml-parsing


【解决方案1】:

试试这个。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-12
    • 1970-01-01
    • 1970-01-01
    • 2013-02-06
    • 2018-08-25
    • 2013-03-23
    • 1970-01-01
    • 2019-11-15
    相关资源
    最近更新 更多