繁体   English   中英

如何在 python 代码中解析多个 xml 文件?

[英]How to parse more than one xml file in python code?

Hi i want to parse 2 xml files in my python code.And want to replace tag value in strings.xml using tags value from config.xml.As i'm new to python i don't have any clue.

这是我的代码:

**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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM