如何使用python按字母顺序对XML排序?

如何使用python按字母顺序对XML排序?,python,xml,elementtree,celementtree,Python,Xml,Elementtree,Celementtree,我有一些XML文件要按元素名排序。这些xml文件被视为my salesforce sandbox/org中的配置文件。我编写了一些代码,将一个xml文件附加到每个配置文件xml文件的底部。允许我一次向多个文件添加代码,而不必复制/粘贴到每个文件。这里的问题是,xml需要按元素名称的字母顺序排序,例如:(ClassAccess、fieldPermissions、layoutAssignments、recordTypeVisibilities、objectPermissions)我在下面粘贴了一个x

我有一些XML文件要按元素名排序。这些xml文件被视为my salesforce sandbox/org中的配置文件。我编写了一些代码,将一个xml文件附加到每个配置文件xml文件的底部。允许我一次向多个文件添加代码,而不必复制/粘贴到每个文件。这里的问题是,xml需要按元素名称的字母顺序排序,例如:(ClassAccess、fieldPermissions、layoutAssignments、recordTypeVisibilities、objectPermissions)我在下面粘贴了一个xml示例。文件的格式需要一致,不能更改,因为salesforce可能不喜欢它

<?xml version="1.0" encoding="UTF-8"?>
<Profile xmlns="http://soap.sforce.com/2006/04/metadata">
    <fieldPermissions>
        <editable>false</editable>
        <field>Branch_Queue__c.Cell_Phone_Number__c</field>
        <readable>true</readable>
    </fieldPermissions>
    <fieldPermissions>
        <editable>false</editable>
        <field>Branch_Queue__c.Branch__c</field>
        <readable>true</readable>
    </fieldPermissions>
    <fieldPermissions>
        <editable>false</editable>
        <field>Branch_Queue__c.Source__c</field>
        <readable>true</readable>
    </fieldPermissions>
    <fieldPermissions>
        <editable>false</editable>
        <field>Branch_Queue__c.Served_By__c</field>
        <readable>true</readable>
    </fieldPermissions>
    <fieldPermissions>
            <editable>false</editable>
            <field>Branch_Queue__c.Update__c</field>
            <readable>true</readable>
    </fieldPermissions>
    <recordTypeVisibilities>
        <default>false</default>
        <recordType>Knowledge__kav.RealEstate</recordType>
        <visible>true</visible>
    </recordTypeVisibilities>
    <recordTypeVisibilities>
        <default>false</default>
        <recordType>Knowledge__kav.RealEstate_Community_Connection</recordType>
        <visible>true</visible>
    </recordTypeVisibilities>
     <objectPermissions>
        <allowCreate>false</allowCreate>
        <allowDelete>false</allowDelete>
        <allowEdit>false</allowEdit>
        <allowRead>true</allowRead>
        <modifyAllRecords>false</modifyAllRecords>
        <object>Branch_Queue__c</object>
        <viewAllRecords>true</viewAllRecords>
    </objectPermissions>
    <classAccesses>
        <apexClass>BranchQueueDisplayList</apexClass>
        <enabled>true</enabled>
    </classAccesses>
    <classAccesses>
        <apexClass>BranchQueueDisplayList_Test</apexClass>
        <enabled>true</enabled>
    </classAccesses>
    <classAccesses>
        <apexClass>BranchQueueService</apexClass>
        <enabled>true</enabled>
    </classAccesses>
</Profile>

假的
分支机构队列移动电话号码
真的
假的
分支队列
真的
假的
分支队列源
真的
假的
分支队列由c提供服务
真的
假的
分支队列更新
真的
假的
知识卡夫房地产
真的
假的
知识、房地产、社区、连接
真的
假的
假的
假的
真的
假的
分支队列
真的
BranchQueueDisplayList
真的
BranchQueueDisplayList\u测试
真的
分支排队服务
真的
如果有帮助,下面是我构建的python脚本。如果您有任何问题,请随时提问。谢谢

import os 
import json
directory = 'C:/Users/HB35401/MAXDev/force-app/main/default/profiles' #folder containing profiles to be modified
os.chdir(directory)
newData = 'C:/testXMLBatch/additionalXML/addXML.xml' #xml file to append to profile-xml files.

for nameOfFile in os.listdir(directory): #for each profile in the directory
    if nameOfFile.endswith(".xml"):
        g = open(newData)
        data = g.read() #set the value of the newXML to the data variable
        f = open(nameOfFile)
        fileContent = f.read() #save the content of the profile to fileContent
        if data in fileContent:
            print('ERROR: XML is already inside the Profile.' + nameOfFile)
        else:
            EndLine = fileContent[-11:] #save the </Profile> tag from the bottom of the file to EndLine variable.
            #print(EndLine)            # theEndLine will be appended back after we add our new XML.
            test = fileContent[:-11] #remove the </Profile> tag and write back to the profile the removal of the </Profile> tag
            with open(nameOfFile, "w") as w:
                w.write(test)
            with open(nameOfFile) as t:
                fileContent2 = t.read()
                #print(fileContent2)   

            h = open(nameOfFile, "a") #add the new data to the profile along with the </Profile> tag
            h.write(data + "\n"+ EndLine)
            h.close()
导入操作系统
导入json
目录='C:/Users/HB35401/MAXDev/force app/main/default/profiles'#包含要修改的配置文件的文件夹
chdir(目录)
newData='C:/testXMLBatch/additionalXML/addXML.xml'#要附加到配置文件xml文件的xml文件。
对于os.listdir(目录)中的nameOfFile:#对于目录中的每个配置文件
如果nameOfFile.endswith(“.xml”):
g=打开(新数据)
data=g.read()#将newXML的值设置为数据变量
f=打开(文件名)
fileContent=f.read()#将配置文件的内容保存到fileContent
如果文件内容中包含数据:
打印('错误:XML已在配置文件中。'+nameOfFile)
其他:
EndLine=fileContent[-11:]#将文件底部的标记保存到EndLine变量。
#print(EndLine)#添加新的XML后,EndLine将被追加回去。
test=fileContent[:-11]#删除标记并将删除的标记写回配置文件
打开(文件名,“w”)为w:
w、 写入(测试)
打开(nameOfFile)为t时:
fileContent2=t.read()
#打印(文件内容2)
h=open(nameOfFile,“a”)#将新数据与标记一起添加到配置文件中
h、 写入(数据+“\n”+结束行)
h、 关闭()
试试这个

from simplified_scrapy import SimplifiedDoc, utils
xml = utils.getFileContent('your xml file.xml')
doc = SimplifiedDoc(xml)
root = doc.Profile
nodes = root.children # Get all nodes

count = len(nodes)
if count:
    sorted_nodes = sorted(nodes, key=operator.itemgetter('tag')) # Sort by tag
    sorted_htmls = []
    for node in sorted_nodes:
        sorted_htmls.append(node.outerHtml) # Get the string of sorted nodes
    for i in range(0, count):
        nodes[i].repleaceSelf(sorted_htmls[i]) # Replace the nodes in the original text with the sorted nodes

print(doc.html)

你自己尝试过分类吗?问题中的代码似乎与排序无关。@mzjn我试图从我在网上找到的几个api中进行排序,但没有成功。我是python新手,我的谷歌搜索还没有被证明是有益的。我想循环遍历xml并获取所有元素及其内容,但我找不到如何执行。@KevinEvery我想循环遍历xml并获取所有元素及其内容,但我找不到如何执行。那是另一个问题。您应该首先使用Python研究XML解析。