Example #1
0
def testLegalChildren():
    dom = Document()
    elem = dom.createElement('element')
    text = dom.createTextNode('text')

    try: dom.appendChild(text)
    except HierarchyRequestErr: pass
    else:
        print("dom.appendChild didn't raise HierarchyRequestErr")

    dom.appendChild(elem)
    try: dom.insertBefore(text, elem)
    except HierarchyRequestErr: pass
    else:
        print("dom.appendChild didn't raise HierarchyRequestErr")

    try: dom.replaceChild(text, elem)
    except HierarchyRequestErr: pass
    else:
        print("dom.appendChild didn't raise HierarchyRequestErr")

    nodemap = elem.attributes
    try: nodemap.setNamedItem(text)
    except HierarchyRequestErr: pass
    else:
        print("NamedNodeMap.setNamedItem didn't raise HierarchyRequestErr")

    try: nodemap.setNamedItemNS(text)
    except HierarchyRequestErr: pass
    else:
        print("NamedNodeMap.setNamedItemNS didn't raise HierarchyRequestErr")

    elem.appendChild(text)
    dom.unlink()
def testLegalChildren():
    dom = Document()
    elem = dom.createElement('element')
    text = dom.createTextNode('text')

    try: dom.appendChild(text)
    except HierarchyRequestErr: pass
    else:
        print "dom.appendChild didn't raise HierarchyRequestErr"

    dom.appendChild(elem)
    try: dom.insertBefore(text, elem)
    except HierarchyRequestErr: pass
    else:
        print "dom.appendChild didn't raise HierarchyRequestErr"

    try: dom.replaceChild(text, elem)
    except HierarchyRequestErr: pass
    else:
        print "dom.appendChild didn't raise HierarchyRequestErr"

    nodemap = elem.attributes
    try: nodemap.setNamedItem(text)
    except HierarchyRequestErr: pass
    else:
        print "NamedNodeMap.setNamedItem didn't raise HierarchyRequestErr"

    try: nodemap.setNamedItemNS(text)
    except HierarchyRequestErr: pass
    else:
        print "NamedNodeMap.setNamedItemNS didn't raise HierarchyRequestErr"

    elem.appendChild(text)
    dom.unlink()
def createXML(IRDtestResults):

	# Create the minidom document
	doc = Document()

	# create the Tests container:
	root = doc.createElement("IRDTests")
	doc.appendChild(root)
	
	#XSL processing instruction:
	pi = doc.createProcessingInstruction('xml-stylesheet',
										 'type="text/xsl" href="testResult.xslt"')
	root = doc.firstChild
	doc.insertBefore(pi, root)

	IRDs = list()
	failedIRDs = list()
	
	# add the test results:
	tests = doc.createElement("Tests")
	root.appendChild(tests)
	for irdResult in IRDtestResults:
		test = doc.createElement("Test")
		test.setAttribute("id", str(irdResult.TestId).lower())
		test.setAttribute("IRD", irdResult.IRD)
		
		if not irdResult.IRD in IRDs:
			IRDs.append(irdResult.IRD)
		
		if(not irdResult.bIsPass):
			if not irdResult.IRD in failedIRDs:
				failedIRDs.append(irdResult.IRD)
		test.setAttribute("pass", str(irdResult.bIsPass).lower())
		tests.appendChild(test)

	IRDs.sort()
	failedIRDs.sort()
	
	#add summary of IRDs:
	IRDsNode = doc.createElement("IRDs")
	root.appendChild(IRDsNode)
	for IRD in IRDs:
		irdNode = doc.createElement("IRD")
		IRDsNode.appendChild(irdNode)
		irdNode.setAttribute("name", IRD)
		bSuccess = True
		if IRD in failedIRDs:
			bSuccess = False
		irdNode.setAttribute("pass", str(bSuccess).lower())
	
	return doc
Example #4
0
def main(args):
  # Input file should be called men.csv
  filename = 'men.csv'
  # The XML nodes will be named <bot>
  single_item = 'bot'
  safe_filename = filename[:-4]
  
  try:
    f = csv.reader(open(filename, 'r'))
  except IOError:
    print('ERROR: Input file men.csv not found in current working directory')
    sys.exit(1)
    
  doc = Document()
  # Use the file name as the root node name
  root_element = doc.createElement(safe_filename)
  doc.appendChild(root_element)
  # Add the style sheet info
  pi = doc.createProcessingInstruction('xml-stylesheet',
                                       'type="text/xsl"'
                                       'href="men.xsl"')
  doc.insertBefore(pi, doc.firstChild)
  # Get the header row from the csv file
  # If it's missing or short, use a default
  columns = next(f)
  if len(columns) < 4:
    columns = ['ipaddress','port','seq_no','active']

  # Remove white space from around column names
  for i in range(len(columns)):
    columns[i] = columns[i].strip()

  # Populate the XML document
  index = 0
  for row in f:
    index += 1
    item = doc.createElement(single_item)
    item.setAttribute('id', str(index))
    root_element.appendChild(item)
    for c in enumerate(create_col_nodes(columns, item, doc)):
      # jpo: Strip white space from node entries
      row[0] = row[0].strip()
      c[1].appendChild(doc.createTextNode(row.pop(0)))
  
  output_file = safe_filename + ".xml"
  # jpo: Add indents and newlines to the XML output
  doc.writexml(open(output_file, 'w'), ' ' * 2, ' ' * 2, '\n') # Write file
  
  print("Done: Created %s" % output_file)
Example #5
0
def main(args):
    # Input file should be called men.csv
    filename = 'men.csv'
    # The XML nodes will be named <bot>
    single_item = 'bot'
    safe_filename = filename[:-4]

    try:
        f = csv.reader(open(filename, 'r'))
    except IOError:
        print(
            'ERROR: Input file men.csv not found in current working directory')
        sys.exit(1)

    doc = Document()
    # Use the file name as the root node name
    root_element = doc.createElement(safe_filename)
    doc.appendChild(root_element)
    # Add the style sheet info
    pi = doc.createProcessingInstruction('xml-stylesheet', 'type="text/xsl"'
                                         'href="men.xsl"')
    doc.insertBefore(pi, doc.firstChild)
    # Get the header row from the csv file
    # If it's missing or short, use a default
    columns = next(f)
    if len(columns) < 4:
        columns = ['ipaddress', 'port', 'seq_no', 'active']

    # Remove white space from around column names
    for i in range(len(columns)):
        columns[i] = columns[i].strip()

    # Populate the XML document
    index = 0
    for row in f:
        index += 1
        item = doc.createElement(single_item)
        item.setAttribute('id', str(index))
        root_element.appendChild(item)
        for c in enumerate(create_col_nodes(columns, item, doc)):
            # jpo: Strip white space from node entries
            row[0] = row[0].strip()
            c[1].appendChild(doc.createTextNode(row.pop(0)))

    output_file = safe_filename + ".xml"
    # jpo: Add indents and newlines to the XML output
    doc.writexml(open(output_file, 'w'), ' ' * 2, ' ' * 2, '\n')  # Write file

    print("Done: Created %s" % output_file)
Example #6
0
# test for xml.dom.minidom
Example #7
0
def exportNmapXML(pcap, out='nmapout-p0f3p.xml', retdom=False):
    import time
    doc = Document()
    pyobj = processCaptures(pcap)
    root = doc.createElement('nmaprun')
    pi = doc.createProcessingInstruction(
        'xml-stylesheet',
        'type="text/xsl" href="file:///usr/local/bin/../share/nmap/nmap.xsl"')
    first = doc.firstChild
    doc.insertBefore(pi, first)
    root.setAttribute('scanner', 'p0fplus')
    t = int(time.time())
    root.setAttribute('start', str(t))
    ftime = time.ctime(t)
    root.setAttribute('startstr', ftime.replace('  ', ' '))
    doc.appendChild(root)
    for k, v in pyobj.items():
        host = doc.createElement('host')
        root.appendChild(host)
        addr = doc.createElement('address')
        addr.setAttribute('addrtype', 'ipv4')
        k = convB2Str(k)
        addr.setAttribute('ipaddr', k)
        host.appendChild(addr)
        hostnames = doc.createElement('hostnames')
        host.appendChild(hostnames)
        if v['hostnames'] is not None:
            for h in v['hostnames']:
                hostname = doc.createElement('hostname')
                if h[-1] == '.':
                    h = h[:-1]
                hostname.setAttribute('name', h)
                hostnames.appendChild(hostname)
        ports = None
        if v['applications'] is not None:
            for app in v['applications']:
                if 'sport' in app:
                    ports = doc.createElement('ports')
                    host.appendChild(ports)
                    port = doc.createElement('port')
                    port.setAttribute(
                        'protocol',
                        'tcp')  # FIXME: change when UDP is supported
                    port.setAttribute('portid', str(app['sport']))
                    ports.appendChild(port)
                    state = doc.createElement('state')
                    state.setAttribute('state', 'open')
                    state.setAttribute('reason', 'push-ack')
                    port.appendChild(state)
                    service = doc.createElement('service')
                    if 'appname' in app:
                        service.setAttribute('product', app['appname'])
                    if 'version' in app:
                        service.setAttribute('version', app['version'])
                    if 'extrainf' in app:
                        service.setAttribute('extrainfo', app['extrainf'])
                    port.appendChild(service)
        if v['otherports'] is not None:
            for portk, value in v['otherports'].items():
                if value['matched'] is False:
                    if ports is None:
                        ports = doc.createElement('ports')
                        host.appendChild(ports)
                    port = doc.createElement('port')
                    port.setAttribute('protocol', 'tcp')
                    port.setAttribute('portid', str(portk))
                    ports.appendChild(port)
                    state = doc.createElement('state')
                    state.setAttribute('state', 'open')
                    reasonstr = flag2str(value['flag'])
                    if reasonstr is not None:
                        state.setAttribute('reason', reasonstr)
                    port.appendChild(state)
        if 'guesses' in v['matches']:
            os = doc.createElement('os')
            host.appendChild(os)
            osmatch = doc.createElement('osmatch')
            for guess in v['matches']['guesses']:
                if guess['type'] != '!':  #is a system
                    osmatch = doc.createElement('osmatch')
                    namematch = ' '.join(
                        guess['label'].split(':')[2:]).replace('.x', '')
                    osmatch.setAttribute('name', namematch)
                    accuracy = str(100 -
                                   guess['distance'])  # best formula ever!
                    osmatch.setAttribute('accuracy', accuracy)
                    os.appendChild(osmatch)
                    osclass = doc.createElement('osclass')
                    osclass.setAttribute('osfamily', guess['os'])
                    osclass.setAttribute('osgen', guess['version'])
                    osclass.setAttribute('accuracy', accuracy)
                    osmatch.appendChild(osclass)
    if retdom is True:
        return doc  # return only the minidom object
    else:
        doc.writexml(open(out, 'w'), indent="  ", addindent="  ", newl='\n')
Example #8
0
#!/usr/bin/python

import sys, os, re
from xml.dom.minidom import Document	

tables=[]
errors=[]
ingroup = False
currenttable = ''


xmlDoc = Document()

pi= xmlDoc.createProcessingInstruction("xml-stylesheet","type=\"text/xsl\" href=\"template.xsl\"")
xmlDoc.insertBefore(pi, xmlDoc.documentElement)

wml = xmlDoc.createElement("database")
xmlDoc.appendChild(wml)

schema = open(sys.argv[1], 'r')
result = file(sys.argv[2],"w")


createTablePattern = re.compile(r'^\s+create_table \"([a-z_-]+)\"',re.M|re.I)
endTablePattern = re.compile(r'^\s+end',re.M|re.I)
fieldPattern = re.compile(r'^\s+t\.[a-z]+\s+\"([a-z0-9-_]+)\"',re.M|re.I)



for i, line in enumerate(schema):
	if re.match('^\s+$',line,re.M|re.I):
Example #9
0
class XmlDataGenerator:
    def __init__(self, xmlTDT, nonXmlPrint=None, xmlStyleData=None):
        from xml.dom.minidom import Document
        self.xmlDoc = Document()
        self.xmlTDT = xmlTDT

        eleCount = 0
        self.eleMap = {}
        for eleTDT in self.xmlTDT:
            self.eleMap[eleTDT['name']] = eleCount
            if eleTDT.__contains__('alias'):
                for eName in eleTDT['alias']:
                    self.eleMap[eName] = eleCount
            eleTDT['ele'] = None
            if not eleTDT.__contains__('cls'):
                eleTDT['cls'] = eleTDT['findex'] + 1
            if not eleTDT.__contains__('sname'):
                eleTDT['sname'] = eleTDT['name']
            if not eleTDT.__contains__('must'):
                eleTDT['must'] = True
            eleCount += 1
        for eleTDT in self.xmlTDT:
            eleTDT['clslist'] = [
                index for index in range(0, eleCount)
                if self.xmlTDT[index]['cls'] > eleTDT['cls']
            ]

        self.topEle = self.__createElement(self.xmlDoc, self.xmlTDT[0])
        if xmlStyleData != None:
            self.xmlDoc.insertBefore(
                self.xmlDoc.createProcessingInstruction(
                    "xml-stylesheet", xmlStyleData), self.topEle)

    def __getFele(self, eleIndex):
        feleIndex = self.xmlTDT[eleIndex]['findex']
        feleTDT = self.xmlTDT[feleIndex]

        if feleIndex > 0:
            fele = feleTDT['ele']
            if fele == None:
                ffele = self.__getFele(feleIndex)
                if feleTDT['must']:
                    fele = self.__createElement(ffele, feleTDT)
                else:
                    fele = ffele
            return fele
        else:
            return self.topEle

    def __createElement(self,
                        fele,
                        eleTDT,
                        content=None,
                        eleName=None,
                        **eleAttrs):
        ele = self.xmlDoc.createElement(
            eleName if eleName != None else eleTDT['sname'])
        eleTDT['ele'] = ele
        fele.appendChild(ele)
        for eleAttr in eleAttrs.keys():
            ele.setAttribute(eleAttr, eleAttrs[eleAttr])
        if content != None:
            ele.appendChild(self.xmlDoc.createCDATASection(content))

        for index in eleTDT['clslist']:
            self.xmlTDT[index]['ele'] = None
        return ele

    def addElement(self, eleName, content=None, **eleAttrs):
        eleIndex = self.eleMap[eleName]
        fele = self.__getFele(eleIndex)
        self.__createElement(fele, self.xmlTDT[eleIndex], content, eleName,
                             **eleAttrs)

    def __str__(self, indent="\t", newl="\n", encoding=None):
        return self.xmlDoc.toprettyxml(indent, newl, encoding)