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 idtag 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 seg_data = pyx12.segment.Segment(reader.Value(), \
48 '~', '*', ':')
49 elif cur_name == 'ele':
50 while reader.MoveToNextAttribute():
51 if reader.Name() == 'id':
52 ele_id = reader.Value()
53
54
55 elif cur_name == 'subele':
56 while reader.MoveToNextAttribute():
57 if reader.Name() == 'id':
58 subele_id = reader.Value()
59 elif tmpNodeType == NodeType['CData2']:
60 if cur_name == 'ele':
61 seg_data.set(ele_id, reader.Value().replace('\n', ''))
62 found_text = True
63 elif cur_name == 'subele':
64 seg_data.set(subele_id, reader.Value().replace('\n', ''))
65 found_text = True
66 elif tmpNodeType == NodeType['text']:
67 if cur_name == 'ele':
68 if ele_id == 'ISA16':
69 subele_term = ':'
70 else:
71 seg_data.set(ele_id, reader.Value())
72 found_text = True
73 elif cur_name == 'subele':
74
75 seg_data.set(subele_id, reader.Value())
76 found_text = True
77 elif tmpNodeType == NodeType['element_end']:
78 cur_name = reader.Name()
79 if cur_name == 'seg':
80 if seg_data.get_seg_id() == 'ISA':
81 seg_str = seg_data.format()
82 fd_out.write(seg_str[:-1] + seg_str[-3] + subele_term + seg_str[-1])
83 else:
84 fd_out.write(seg_data.format())
85 fd_out.write('\n')
86 elif cur_name == 'ele':
87 if not found_text:
88 seg_data.set(ele_id, '')
89 found_text = True
90 ele_id = None
91 elif cur_name == 'subele' and not found_text:
92
93 seg_data.set(subele_id, '')
94 found_text = True
95 subele_id = None
96 elif cur_name == 'comp':
97
98 subele_id = None
99 cur_name = None
100 ret = reader.Read()
101 except:
102 logger.error('Read of file "%s" failed' % (filename))
103 raise
104 return False
105 return True
106