File: xincludator.py

package info (click to toggle)
empathy 3.12.12-4
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 39,236 kB
  • ctags: 9,900
  • sloc: ansic: 88,918; sh: 11,576; python: 3,185; makefile: 1,824; xml: 1,249
file content (46 lines) | stat: -rw-r--r-- 1,421 bytes parent folder | download | duplicates (15)
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
#!/usr/bin/python

import sys
from sys import argv, stdout, stderr
import codecs, locale
import os
import xml.dom.minidom

if sys.version_info[0] < 3:
    stdout = codecs.getwriter('utf-8')(stdout)

NS_XI = 'http://www.w3.org/2001/XInclude'

def xincludate(dom, base, dropns = []):
    remove_attrs = []
    for i in range(dom.documentElement.attributes.length):
        attr = dom.documentElement.attributes.item(i)
        if attr.prefix == 'xmlns':
            if attr.localName in dropns:
                remove_attrs.append(attr)
            else:
                dropns.append(attr.localName)
    for attr in remove_attrs:
        dom.documentElement.removeAttributeNode(attr)
    for include in dom.getElementsByTagNameNS(NS_XI, 'include'):
        href = include.getAttribute('href')
        # FIXME: assumes Unixy paths
        filename = os.path.join(os.path.dirname(base), href)
        subdom = xml.dom.minidom.parse(filename)
        xincludate(subdom, filename, dropns)
        if './' in href:
            subdom.documentElement.setAttribute('xml:base', href)
        include.parentNode.replaceChild(subdom.documentElement, include)

if __name__ == '__main__':
    argv = argv[1:]
    dom = xml.dom.minidom.parse(argv[0])
    xincludate(dom, argv[0])

    if sys.version_info[0] >= 3:
        xml = dom.toxml(encoding=None)
    else:
        xml = dom.toxml()

    stdout.write(xml)
    stdout.write('\n')