ElementTree排序问题

本文介绍如何通过修改ElementTree源代码来禁用XML属性的默认排序行为,包括去除属性排序及基于命名空间的排序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://stackoverflow.com/questions/14257978/elementtree-setting-attribute-order



Apply monkey patch as mentioned below:: 
in 
ElementTree.py file, there is a functionnamed as _serialize_xml
in this function; apply the below mentioned patch;

       ##for k, v in sorted(items):  # remove the sorted here

       for k, v in items:

           if isinstance(k, QName):

               k = k.text

           if isinstance(v, QName):

               v = qnames[v.text]

           else:

               v = _escape_attrib(v, encoding)

           write(" %s=\"%s\"" % (qnames[k], v))

here; remove the sorted(items) andmake it just items like i have doneabove. 

Also to disable sorting based on namespace(because in above patch; sorting isstill present when namespace is present for xml attribute; otherwise ifnamespace is not present; then above is working fine); so to do that, replaceall 
{} with collections.OrderedDict() from ElementTree.py 

 

0a1,52
> #
> # ElementTree
> # $Id: ElementTree.py 3440 2008-07-18 14:45:01Z fredrik $
> #
> # light-weight XML support for Python 2.3 and later.
> #
> # history (since 1.2.6):
> # 2005-11-12 fl   added tostringlist/fromstringlist helpers
> # 2006-07-05 fl   merged in selected changes from the 1.3 sandbox
> # 2006-07-05 fl   removed support for 2.1 and earlier
> # 2007-06-21 fl   added deprecation/future warnings
> # 2007-08-25 fl   added doctype hook, added parser version attribute etc
> # 2007-08-26 fl   added new serializer code (better namespace handling, etc)
> # 2007-08-27 fl   warn for broken /tag searches on tree level
> # 2007-09-02 fl   added html/text methods to serializer (experimental)
> # 2007-09-05 fl   added method argument to tostring/tostringlist
> # 2007-09-06 fl   improved error handling
> # 2007-09-13 fl   added itertext, iterfind; assorted cleanups
> # 2007-12-15 fl   added C14N hooks, copy method (experimental)
> #
> # Copyright (c) 1999-2008 by Fredrik Lundh.  All rights reserved.
> #
> # fredrik@pythonware.com
> # http://www.pythonware.com
> #
> # --------------------------------------------------------------------
> # The ElementTree toolkit is
> #
> # Copyright (c) 1999-2008 by Fredrik Lundh
> #
> # By obtaining, using, and/or copying this software and/or its
> # associated documentation, you agree that you have read, understood,
> # and will comply with the following terms and conditions:
> #
> # Permission to use, copy, modify, and distribute this software and
> # its associated documentation for any purpose and without fee is
> # hereby granted, provided that the above copyright notice appears in
> # all copies, and that both that copyright notice and this permission
> # notice appear in supporting documentation, and that the name of
> # Secret Labs AB or the author not be used in advertising or publicity
> # pertaining to distribution of the software without specific, written
> # prior permission.
> #
> # SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
> # TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
> # ABILITY AND FITNESS.  IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR
> # BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
> # DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
> # WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
> # ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
> # OF THIS SOFTWARE.
> # --------------------------------------------------------------------
2c54,55
< import collections
---
> # Licensed to PSF under a Contributor Agreement.
> # See http://www.python.org/psf/license for licensing details.
74c127
<     import ElementPath
---
>     from . import ElementPath
154c207
<     def __init__(self, tag, attrib=collections.OrderedDict(), **extra):
---
>     def __init__(self, tag, attrib={}, **extra):
474c527
< def SubElement(parent, tag, attrib=collections.OrderedDict(), **extra):
---
> def SubElement(parent, tag, attrib={}, **extra):
785c838
<     namespaces = collections.OrderedDict()
---
>     namespaces = {}
865c918,919
<                     for v, k in (namespaces.items()):  # sort on prefix
---
>                     for v, k in sorted(namespaces.items(),
>                                        key=lambda x: x[1]):  # sort on prefix
872c926
<                 for k, v in items:  # lexical order
---
>                 for k, v in sorted(items):  # lexical order
1264c1318
<     ids = collections.OrderedDict()
---
>     ids = {}
1420c1474
<         self._names = collections.OrderedDict() # name memo cache
---
>         self._names = {} # name memo cache
1442c1496
<         self.entity = collections.OrderedDict()
---
>         self.entity = {}
1476c1530
<         attrib = collections.OrderedDict()
---
>         attrib = {}
1485c1539
<         attrib = collections.OrderedDict()
---
>         attrib = {}

### 实现 el-tree 节点排序功能 在 Element UI 的 `el-tree` 组件中,默认并未提供内置的节点排序功能。然而,可以通过自定义逻辑来实现这一目标。以下是具体方法: #### 方法一:通过调整数据源顺序 由于 `el-tree` 是基于传入的数据渲染的,因此可以在前端对数据进行预处理并重新设置其顺序。 ```javascript // 假设 treeData 是原始树形结构数据 function sortTreeNodes(treeData, key) { return treeData.sort((a, b) => a[key] - b[key]).map(item => { if (item.children && item.children.length > 0) { item.children = sortTreeNodes(item.children, key); } return item; }); } // 使用示例 this.treeData = sortTreeNodes(this.studentTree, 'order'); // order 字段用于表示排序依据 ``` 上述代码会递归遍历整个树结构并对每一层按照指定字段(如 `order` 或其他数值型字段)进行升序排列[^1]。 --- #### 方法二:动态拖拽排序 如果希望用户能够手动调整节点位置,则可以借助第三方库 `vue-draggable` 来增强交互体验。 安装依赖: ```bash npm install vuedraggable --save ``` 引入组件并配置: ```html <template> <div> <draggable v-model="treeData" :options="{ group: 'description' }"> <el-tree ref="tree" :data="treeData" node-key="id" draggable @node-drop="handleDrop" > <span slot-scope="{ node, data }">{{ node.label }}</span> </el-tree> </draggable> </div> </template> <script> import draggable from "vuedraggable"; export default { components: { draggable }, data() { return { treeData: [ { id: 1, label: "Node 1", children: [{ id: 2, label: "Child Node 1" }], }, { id: 3, label: "Node 2" }, ], }; }, methods: { handleDrop(event) { console.log("Dropped", event); }, }, }; </script> ``` 此方式允许用户直接操作界面完成排序,并可通过事件监听器捕获变化后的结果以便保存至数据库或其他存储介质[^2]。 --- #### 方法三:利用插槽定制化展示 当需要更复杂的排序规则时,可考虑使用作用域插槽来自定义每项的内容及其行为。例如,在某些场景下可能还需要额外按钮触发特定动作来进行局部重排等操作。 ```html <el-tree :data="sortedData"> <template #default="{ node, data }"> <span>{{ node.label }} ({ data.order })</span> <!-- 显示当前优先级 --> <button @click.stop="moveUp(data)">上移</button> <button @click.stop="moveDown(data)">下移</button> </template> </el-tree> ``` 配合 JavaScript 定义移动函数: ```javascript methods: { moveUp(node) { const index = this.sortedData.indexOf(node); if (index === 0 || !~index) return; [this.sortedData[index], this.sortedData[index - 1]] = [this.sortedData[index - 1], this.sortedData[index]]; }, moveDown(node) { const index = this.sortedData.indexOf(node); if (index >= this.sortedData.length - 1 || !~index) return; [this.sortedData[index], this.sortedData[index + 1]] = [this.sortedData[index + 1], this.sortedData[index]]; }, } ``` 这种方法灵活性较高,适合复杂业务需求下的个性化开发[^3]。 --- ### 总结 以上三种方案分别适用于不同情况下的节点排序需求——静态初始化、动态交互以及高度客制化的场合均可满足实际项目中的多样化诉求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值