1
2
3
4
5
6
7
8
9
10
11
12
13 """
14 Create an X12 document from a XML data file in the simple form
15 """
16
17 import libxml2
18 import logging
19
20
21 import pyx12.segment
22
23 NodeType = {'element_start': 1, 'element_end': 15, 'attrib': 2, 'text': 3,
24 'CData': 4, 'entity_ref': 5, 'entity_decl':6, 'pi': 7, 'comment': 8,
25 'doc': 9, 'dtd': 10, 'doc_frag': 11, 'notation': 12, 'CData2': 14}
26
28 """
29 Convert a XML file in simple X12 form to an X12 file
30 @param filename: libxml2 requires a file name. '-' gives stdin
31 @type filename: string
32 @param fd_out: Output file
33 @type fd_out: file descripter
34 """
35 logger = logging.getLogger('pyx12')
36 try:
37 reader = libxml2.newTextReaderFilename(filename)
38 ret = reader.Read()
39 found_text = False
40 subele_term = ''
41 while ret == 1:
42 tmpNodeType = reader.NodeType()
43 if tmpNodeType == NodeType['element_start']:
44 found_text = False
45 cur_name = reader.Name()
46 if cur_name == 'seg':
47 while reader.MoveToNextAttribute():
48 if reader.Name() == 'id':
49
50 seg_data = pyx12.segment.Segment(reader.Value(), \
51 '~', '*', ':')
52 elif cur_name == 'ele':
53 while reader.MoveToNextAttribute():
54 if reader.Name() == 'id':
55 ele_id = reader.Value()
56
57
58 elif cur_name == 'subele':
59 while reader.MoveToNextAttribute():
60 if reader.Name() == 'id':
61 subele_id = reader.Value()
62 elif tmpNodeType == NodeType['CData2']:
63 if cur_name == 'ele':
64 seg_data.set(ele_id, reader.Value().replace('\n', ''))
65 found_text = True
66 elif cur_name == 'subele':
67 seg_data.set(subele_id, reader.Value().replace('\n', ''))
68 found_text = True
69 elif tmpNodeType == NodeType['text']:
70 if cur_name == 'ele':
71 if ele_id == 'ISA16':
72 subele_term = ':'
73 else:
74 seg_data.set(ele_id, reader.Value())
75 found_text = True
76 elif cur_name == 'subele':
77
78 seg_data.set(subele_id, reader.Value())
79 found_text = True
80 elif tmpNodeType == NodeType['element_end']:
81 cur_name = reader.Name()
82 if cur_name == 'seg':
83 if seg_data.get_seg_id() == 'ISA':
84 seg_str = seg_data.format()
85 fd_out.write(seg_str[:-1] + seg_str[-3] + subele_term + seg_str[-1])
86 else:
87 fd_out.write(seg_data.format())
88 fd_out.write('\n')
89 elif cur_name == 'ele':
90 if not found_text:
91 seg_data.set(ele_id, '')
92 found_text = True
93 ele_id = None
94 elif cur_name == 'subele' and not found_text:
95
96 seg_data.set(subele_id, '')
97 found_text = True
98 subele_id = None
99 elif cur_name == 'comp':
100
101 subele_id = None
102 cur_name = None
103 ret = reader.Read()
104 except:
105 logger.error('Read of file "%s" failed' % (filename))
106 raise
107 return False
108 return True
109