使用python将带有内容的标签添加到现有XML(resx)

我有一个带有许多字符串的XML:

https://webappname.azurewebsites.net/.auth/me

我想将这些字符串附加到具有以下格式的一长串字符串的resx文件中:

<?xml version="1.0" encoding="UTF-8"?>
  <Strings>
    <String id="TEST_STRING_FROM_XML">
      <en>Test string from XML</en>
      <de>Testzeichenfolge aus XML</de>
      <es>Cadena de prueba de XML</es>
      <fr>Tester la chaîne à partir de XML</fr>
      <it>Stringa di test da XML</it>
      <ja>XMLからのテスト文字列</ja>
      <ko>XML에서 테스트 문자열</ko>
      <nl>Testreeks van XML</nl>
      <pl>Łańcuch testowy z XML</pl>
      <pt>Cadeia de teste de XML</pt>
      <ru>Тестовая строка из XML</ru>
      <sv>Teststräng från XML</sv>
      <zh-CHS>从XML测试字符串</zh-CHS>
      <zh-CHT>從XML測試字符串</zh-CHT>
      <Comment>A test string that comes from a shared XML file.</Comment>
    </String>
    <String id="TEST_STRING_FROM_XML_2">
      <en>Another test string from XML.</en>
      <de></de>
      <es></es>
      <fr></fr>
      <it></it>
      <ja></ja>
      <ko></ko>
      <nl></nl>
      <pl></pl>
      <pt></pt>
      <ru></ru>
      <sv></sv>
      <zh-CHS></zh-CHS>
      <zh-CHT></zh-CHT>
      <Comment>Another test string that comes from a shared XML file.</Comment>
    </String>
  </Strings>

但是使用以下python代码段:

<?xml version="1.0" encoding="utf-8"?>
<root>
  <!-- 
    microsoft ResX Schema 
    
    Version 2.0
    
    **a bunch of schema and header stuff...**
    -->
    
  <data name="STRING_NAME_1" xml:space="preserve">
    <value>This is a value 1</value>
    <comment>This is a comment 1</comment>
  </data>
  <data name="STRING_NAME_2" xml:space="preserve">
    <value>This is a value 2</value>
    <comment>This is a comment 2</comment>
  </data>
</root>

我将以下XML附加到resx文件的末尾:

import sys,os,os.path,re
import xml.etree.ElementTree as ET
from xml.dom import minidom

existingStrings = []
newStrings = {}
languages = []

resx = '*path to resx file*'


def LoadAllNewStrings():

    src_root = ET.parse('Strings.xml').getroot()

    for src_string in src_root.findall('String'):

        src_id = src_string.get('id')

        src_value = src_string.findtext("en")
        src_comment = src_string.findtext("Comment")

        content = [src_value,src_comment]

        newStrings[src_id] = content


def ExscludeExistingStrings():
    dest_root = ET.parse(resx)
    for stringName in dest_root.findall('Name'):
        for stringId in newStrings:
            if stringId == stringName:
                newStrings.remove(stringId)


def PrettifyXML(element):

    roughString = ET.tostring(element,'utf-8')
    reparsed = minidom.parseString(roughString)
    return reparsed.toprettyxml(indent="  ")


def AddMissingStringsToLocalResource():

    ExscludeExistingStrings()
    
    with open(resx,"a") as output:
        root = ET.parse(resx).getroot()

        for newString in newStrings:
            
            data = ET.Element("data",name=newString)

            newStringContent = newStrings[newString]
            newStringValue = newStringContent[0]
            newStringComment = newStringContent[1]

            ET.SubElement(data,"value").text = newStringValue
            ET.SubElement(data,"comment").text = newStringComment

            output.write(PrettifyXML(data))


if __name__ == "__main__":
    LoadAllNewStrings()
    AddMissingStringsToLocalResource()

即根结尾,然后添加新字符串。关于如何将数据标签正确添加到现有根目录的任何想法?

iCMS 回答:使用python将带有内容的标签添加到现有XML(resx)

with open(resx,"a") as output:

。请勿将XML文件作为文本文件打开。不是为了阅读,不是为了写作,不是为了追加。永远不会。

XML文件的典型生命周期为:

  • 解析(使用XML解析器)
  • 阅读或修改(使用DOM API)
  • 如果有更改:Serializition(也使用DOM API)

您绝对不应在XML文件上调用open()。 XML文件不应被视为纯文本。他们不是。

# parsing
resx = ET.parse(resx_path)
root = resx.getroot()

# modification
for newString in newStrings:
    newStringContent = newStrings[newString]

    # create node
    data = ET.Element("data",name=newString)
    ET.SubElement(data,"value").text = newStringContent[0]
    ET.SubElement(data,"comment").text = newStringContent[1]
    
    # append node,e.g. to the top level element
    root.append(data)
    
# serialization
resx.write(resx_path,encoding='utf8')
本文链接:https://www.f2er.com/2052789.html

大家都在问