项目中需要添加多语言, 安卓的字符文件都放在.xml中,已经整理的很好了, iOS这边只需要将xml文件转成OC的string文件就可以使用.
使用Python 3 写了一个脚本, 可以修改xml文件和oc文件后,就可以自动将xml文件读取并写入到OC文件中.
这个demo还不够完善, 目前一次只能写入一个语言. 后面如果有需求会再完善.
项目中使用了 xmltodict来读取xml. xmltodict的安装非常简单只需要在命令行中输入一行命令即可.
pip3 install xmltodict
因为是使用Python 3所以使用了 pip3. 如果使用Python 2. 可以直接用pip
关于xmltodict的安装 https://blog.csdn.net/Baby_come_here/article/details/82688020
项目代码 https://gitee.com/CCSunIsland/CCXmlToLangCode.git
主要的项目代码
读取XML
def readXML(path):
ocString = []
with open(path) as fd:
obj = xmltodict.parse(fd.read())
resources = obj["resources"]
strings = resources["string"]
nameKey = "@name"
valueKey = "#text"
for item in strings:
value = ""
key = ""
for k, v in item.items():
if k == nameKey:
key = v
if k == valueKey:
value = v
singleStr = "\""+key + "\"" + " = " + "\"" + value + "\"" + ";" + "\n"
ocString.append(singleStr)
return ocString
写入
def writeFileWithList(lines, filePath):
with open(filePath, 'a') as f:
for itme in lines:
f.write(itme)
调用
import CCReadXMLToList
import CCWriteListToFile
directoryXML = "/Users/aaa/Desktop/String" # xml路径
fileNameXML = ['strings', 'strings1','strings2','strings3','strings4'] # xml文件名
suffixXML = ".xml"
directoryOC = "/Users/aaa/Desktop/backup/test/test" #oc文件路径
fileNameOC = ["zh-Hans.lproj"]
suffixOC = "InfoPlist.strings"
pathOC = directoryOC + "/" + fileNameOC[0] + "/" + suffixOC # oc的路径
for name in fileNameXML:
path = directoryXML + "/" + name + suffixXML
firstLine = "//" + name + "\n\n\n" # 安卓分模块了, oc我准备写在一个string 文件内部, 为了区分, 在每个安卓模块前加上了 文件名和三个换行
CCWriteListToFile.writeFileWithList([firstLine], pathOC)
# result = CCWriteListToFile.readXML(path)
result = CCReadXMLToList.readXML(path)
CCWriteListToFile.writeFileWithList(result, pathOC)