Repository navigation
Expand file tree
/
Copy path3.py
More file actions
182 lines (161 loc) · 5.62 KB
/
Copy path3.py
File metadata and controls
182 lines (161 loc) · 5.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
import json
import xml.etree.ElementTree as ET
from typing import Dict, Any, List, Optional
import json
import xml.etree.ElementTree as ET
from typing import Dict, Any, List, Optional, Union
def xml_to_json_schema(
xml_string: str,
include_values: bool = True,
include_metadata: bool = True,
metadata_defaults: Optional[Dict[str, Any]] = None
) -> List[Dict[str, Any]]:
if metadata_defaults is None:
metadata_defaults = {
"alias": "",
"disabled": False,
"device_type": "",
"device_id": "",
"ref_var": "",
"pipeline_value": ""
}
root = ET.fromstring(xml_string)
def build_with_count(elem: ET.Element, parent_key: str, siblings: List[ET.Element]) -> Dict[str, Any]:
tag = elem.tag
if '}' in tag:
tag = tag.split('}', 1)[1]
# 计算同标签索引
count = 0
for sib in siblings:
sib_tag = sib.tag
if '}' in sib_tag:
sib_tag = sib_tag.split('}', 1)[1]
if sib_tag == tag:
if sib is elem:
break
count += 1
if parent_key == '':
key = tag
else:
key = f"{parent_key}/{tag}[{count}]"
node = {
"key": key,
"identifier": tag,
"name": tag,
"kind": "element",
"children": []
}
if include_values and elem.text and elem.text.strip():
node["text"] = elem.text.strip()
# 处理属性
for attr_name, attr_value in elem.attrib.items():
if '}' in attr_name:
attr_name = attr_name.split('}', 1)[1]
attr_key = f"{key}/@{attr_name}"
attr_node = {
"key": attr_key,
"identifier": attr_name,
"name": attr_name,
"kind": "attribute"
}
if include_values:
attr_node["value"] = attr_value
# 注入元数据字段
if include_metadata:
for k, default_val in metadata_defaults.items():
attr_node[k] = default_val
node["children"].append(attr_node)
# 处理子元素
children_elems = list(elem)
for child in children_elems:
child_node = build_with_count(child, key, children_elems)
node["children"].append(child_node)
return node
# 根节点处理
root_tag = root.tag
if '}' in root_tag:
root_tag = root_tag.split('}', 1)[1]
root_key = root_tag
root_node = {
"key": root_key,
"identifier": root_tag,
"name": root_tag,
"kind": "element",
"children": []
}
# 根属性
for attr_name, attr_value in root.attrib.items():
if '}' in attr_name:
attr_name = attr_name.split('}', 1)[1]
attr_key = f"{root_key}/@{attr_name}"
attr_node = {
"key": attr_key,
"identifier": attr_name,
"name": attr_name,
"kind": "attribute"
}
if include_values:
attr_node["value"] = attr_value
if include_metadata:
for k, default_val in metadata_defaults.items():
attr_node[k] = default_val
root_node["children"].append(attr_node)
# 根子元素
root_children = list(root)
for child in root_children:
child_node = build_with_count(child, root_key, root_children)
root_node["children"].append(child_node)
return [root_node]
# ---------- 使用示例 ----------
if __name__ == '__main__':
xml_str = '''<?xml version="1.0" encoding="UTF-8"?>
<Message id="MSG-1001" type="inspect" version="1.0">
<Header timestamp="2026-08-18 16:37:00" source="msmq">
<Queue name="Vision.Result" mode="write" />
</Header>
<Body>
<Product sn="P20260818001" model="A12" result="OK">
<Station id="ST-01" name="外观检测" />
<Defect count="2">
<Item code="scratch" level="ng" x="120" y="80" />
<Item code="stain" level="ok" x="45" y="210" />
</Defect>
</Product>
</Body>
</Message>'''
xml_str2 = '''<?xml version="1.0" encoding="UTF-8"?>
<Order id="ORD-2026-001" date="2026-08-19" status="pending">
<Customer id="CUST-1001" type="vip">
<Name>张伟</Name>
<Email>zhang.wei@example.com</Email>
</Customer>
<Items count="3">
<Item id="P001" price="299.99" quantity="1">
<Description>智能手机 128GB</Description>
</Item>
<Item id="P002" price="89.50" quantity="2">
<Description>无线耳机</Description>
</Item>
<Item id="P003" price="19.99" quantity="5">
<Description>USB-C 数据线</Description>
</Item>
</Items>
<Note>请尽快发货,客户急需。</Note>
</Order>'''
xml_str3 = '''<?xml version='1.0' encoding='utf-8'?>
<Library name="Tech Books">
<Book id="B001">
<Title>Python 编程</Title>
</Book>
<Book id="B002">
<Title>数据科学入门</Title>
</Book>
<Book id="B003">
<Title>算法导论</Title>
</Book>
</Library>'''
xml_str4 = '''<?xml version='1.0' encoding='utf-8'?>
<result><job bsn="driver" barcode="D1234567X01" jobtype="" overallresult="pass" /><tester name="super_ctl" lane="1" version="1.10" /><tests performed="2026-08-19 17:25:54" cycletime="" faultcode="" faultmessage=""><test name="super_ctl" result="pass" value="pass" status="" expectedvalue="" lowerlimit="" upperlimit="" units="" /></tests></result>
'''
schema_with_values = xml_to_json_schema(xml_str4, include_values=True)
print(json.dumps(schema_with_values, indent=2, ensure_ascii=False))