当前位置: 首页>>代码示例>>Python>>正文


Python Document.createCDATASection方法代码示例

本文整理汇总了Python中xml.dom.minidom.Document.createCDATASection方法的典型用法代码示例。如果您正苦于以下问题:Python Document.createCDATASection方法的具体用法?Python Document.createCDATASection怎么用?Python Document.createCDATASection使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在xml.dom.minidom.Document的用法示例。


在下文中一共展示了Document.createCDATASection方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: createfilexml

# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import createCDATASection [as 别名]
 def createfilexml(self):
     
     global Mpath,Magent
     homep=Mpath
     if not os.path.isdir(homep+"/xssalertdefault"):
         os.mkdir(homep+"/xssalertdefault")
     
     f1=open(homep+"/xssalertdefault/payload.xml","w")
     f2=open(homep+"/xssalertdefault/header.xml","w")
     f3=open(homep+"/xssalertdefault/url.xml","w")
     
     dom1=Document()
     x=dom1.createElement("xssalert")
     dom1.appendChild(x)
     i=0
     while i < 2:
         xa=dom1.createElement("xssalertvector")
         x.appendChild(xa)
         vr=dom1.createElement("vector")
         xa.appendChild(vr)
         testvr=dom1.createCDATASection("??")
         vr.appendChild(testvr)
         i=i+1
     f1.write(dom1.toprettyxml("  "))
     
     dom2=Document()
     y=dom2.createElement("xssalert")
     dom2.appendChild(y)
     i=0
     while i<2:
         xb=dom2.createElement("xssalertheader")
         y.appendChild(xb)
         hr=dom2.createElement("header")
         xb.appendChild(hr)
         testhr=dom2.createCDATASection("??")
         hr.appendChild(testhr)
         i=i+1
     f2.write(dom2.toprettyxml("  "))
     
     dom3=Document()
     z=dom3.createElement("xssalert")
     dom3.appendChild(z)
     i=0
     while i<2:
         xc=dom3.createElement("xssalerturl")
         z.appendChild(xc)
         ur=dom3.createElement("url")
         xc.appendChild(ur)
         testhr=dom3.createCDATASection("??")
         ur.appendChild(testhr)
         i=i+1
     f3.write(dom3.toprettyxml("  "))
     
     f1.close()
     f2.close()
     f3.close()
     
     self.file_create_alert.setText("Default directory with XML files Created in '"+homep+"'  \n  Replace '??' with your text")    
开发者ID:arjunjain,项目名称:xssalert,代码行数:60,代码来源:xssverify.py

示例2: pts2xml

# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import createCDATASection [as 别名]
def pts2xml(ptsFile, xmlFile=None):
	if xmlFile == None:
		xmlFile = ptsFile[:-4] + ".xml"
	
	try:
		f = open(ptsFile, 'r')
		fileContent = f.read().split()
	
	except IOError:
		print "File: %s not found.\n" % asfFile
		
	else:	
		start =  fileContent.index("{") + 1
		end = fileContent.index("}")
		pts = []
		while start < end:
			pts.append((float(fileContent[start]),float(fileContent[start+1])))
			start += 2
		f.close()
			
		doc = Document()

		annotation = doc.createElement("annotation")
		doc.appendChild(annotation)

		objects = doc.createElement("objects")
		objects.setAttribute("type", "points")
		objects.setAttribute("count", "%.0f" % len(pts))
		annotation.appendChild(objects)

		text = ""
		for (x,y) in pts:
			text += "%.0f %.0f\n" % (x,y)
		cDataSection = doc.createCDATASection(text)
		objects.appendChild(cDataSection)

		objects = doc.createElement("objects")
		objects.setAttribute("type", "rectangles")
		objects.setAttribute("count", "int")
		annotation.appendChild(objects)
		
		cDataSection = doc.createCDATASection("\n")
		objects.appendChild(cDataSection)

		xml = open(xmlFile, 'w')
		xml.write(doc.toprettyxml(indent="  ", encoding="UTF-8"))
		xml.close()
开发者ID:Flipajs,项目名称:pilab-annotator,代码行数:49,代码来源:converter.py

示例3: toWorkspaceXml

# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import createCDATASection [as 别名]
    def toWorkspaceXml(self, quantity=1, data=None):

        launchData = {}
        if self.data != None:
            for key in self.data:
                launchData[key] = self.data[key]
        if data != None:
            for key in data:
                launchData[key] = data[key]

        # why did I think this was a good idea?

        doc = Document()
        cluster = doc.createElementNS("http://www.globus.org/2008/06/workspace/metadata/logistics", "cluster")

        workspace = doc.createElement("workspace");
        cluster.appendChild(workspace)

        name = doc.createElement("name")
        name.appendChild(doc.createTextNode(self.name))
        workspace.appendChild(name)

        image = doc.createElement("image")
        image.appendChild(doc.createTextNode(self.ami))
        workspace.appendChild(image)

        quantityNode = doc.createElement("quantity")
        quantityNode.appendChild(doc.createTextNode(str(quantity)))
        workspace.appendChild(quantityNode)

        nic = doc.createElement("nic")
        nic.setAttribute("wantlogin","true")
        nic.appendChild(doc.createTextNode("public"))
        workspace.appendChild(nic)

        ctx = doc.createElement("ctx")
        workspace.appendChild(ctx)

        provides = doc.createElement("provides")
        provides.appendChild(doc.createElement("identity"))
        ctx.appendChild(provides)

        role = doc.createElement("role")
        role.setAttribute("hostname","true")
        role.setAttribute("pubkey","true")
        role.appendChild(doc.createTextNode(self.name))
        provides.appendChild(role)

        requires = doc.createElement("requires")
        requires.appendChild(doc.createElement("identity"))
        ctx.appendChild(requires)

        for key in launchData:
            dataNode = doc.createElement("data")
            dataNode.setAttribute("name", key)
            dataNode.appendChild(doc.createCDATASection(launchData[key]))
            requires.appendChild(dataNode)
        
        return cluster.toxml()
开发者ID:clemesha-ooi,项目名称:ctx-broker-scalability-harness,代码行数:61,代码来源:cpe_provisioner_ec2.py

示例4: saveAnnotations

# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import createCDATASection [as 别名]
    def saveAnnotations(self):
        "Currently supports only saving xml files"
        global points, path, lastSavedState, annotationChanged
        filename = os.path.splitext(str(self.ui.imageComboBox.currentText()))[0]
        filePath = os.path.join(str(path), str(filename) + ".xml")
        currentIndex = self.ui.imageComboBox.currentIndex()
        lastSavedState = self.undoStacks[currentIndex].index()
        annotationChanged[currentIndex] = False
       
        doc = Document()
        
        annotation = doc.createElement("annotation")
        doc.appendChild(annotation)
		
        objects = doc.createElement("objects")
        objects.setAttribute("type", "points")
        objects.setAttribute("count", "%.0f" % len(points[currentIndex]))
        annotation.appendChild(objects)
		
        text = ""
        for (x,y) in points[currentIndex]:
            text += "%.0f %.0f\n" % (x,y)
        if text == "":
			text = "\n"
        cDataSection = doc.createCDATASection(text)
        objects.appendChild(cDataSection)

        objects = doc.createElement("objects")
        objects.setAttribute("type", "rectangles")
        objects.setAttribute("count", "%.0f" % len(rectangles[currentIndex]))
        annotation.appendChild(objects)
		
        text = ""
        for (x,y,w,h) in rectangles[currentIndex]:
            text += "%.0f %.0f %.0f %.0f\n" % (x,y,w,h)
        if text == "":
			text = "\n"
        cDataSection = doc.createCDATASection(text)
        objects.appendChild(cDataSection)

        f = open(filePath, 'w')
        f.write(doc.toprettyxml(indent="  ", encoding="UTF-8"))
        f.close()
        
        self.ui.statusBar.showMessage("File saved to %s" % (filePath))
        self.setWindowTitle("%s (%s) - pilab-annotator" % (self.ui.imageComboBox.currentText(), path))
开发者ID:Flipajs,项目名称:pilab-annotator,代码行数:48,代码来源:annotator.py

示例5: render

# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import createCDATASection [as 别名]
    def render(self, summary=True, messages=True, profile=False):
        xml_doc = Document()

        testsuite_el = xml_doc.createElement('testsuite')
        testsuite_el.setAttribute('errors', str(self.summary['message_count']))
        testsuite_el.setAttribute('failures', '0')
        testsuite_el.setAttribute('name', 'prospector-%s' % '-'.join(self.summary['tools']))
        testsuite_el.setAttribute('tests', str(self.summary['message_count']))
        testsuite_el.setAttribute('time', str(self.summary['time_taken']))
        xml_doc.appendChild(testsuite_el)

        prop_el = xml_doc.createElement('properties')
        testsuite_el.appendChild(prop_el)

        sysout_el = xml_doc.createElement('system-out')
        sysout_el.appendChild(xml_doc.createCDATASection(''))
        testsuite_el.appendChild(sysout_el)

        syserr_el = xml_doc.createElement('system-err')
        syserr_el.appendChild(xml_doc.createCDATASection(''))
        testsuite_el.appendChild(syserr_el)

        for message in sorted(self.messages):
            testcase_el = xml_doc.createElement('testcase')
            testcase_el.setAttribute('name', '%s-%s' % (message.location.path, message.location.line))

            failure_el = xml_doc.createElement('error')
            failure_el.setAttribute('message', message.message.strip())
            failure_el.setAttribute('type', '%s Error' % message.source)
            template = '%(path)s:%(line)s: [%(code)s(%(source)s), %(function)s] %(message)s'
            cdata = template % {
                'path': message.location.path,
                'line': message.location.line,
                'source': message.source,
                'code': message.code,
                'function': message.location.function,
                'message': message.message.strip()
            }
            failure_el.appendChild(xml_doc.createCDATASection(cdata))

            testcase_el.appendChild(failure_el)

            testsuite_el.appendChild(testcase_el)

        return xml_doc.toprettyxml()
开发者ID:benoit-pierre,项目名称:prospector,代码行数:47,代码来源:xunit.py

示例6: generate_cluster_document

# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import createCDATASection [as 别名]
def generate_cluster_document(image, name="domain_instance", quantity=1,
                              nic="public", wantlogin="true", chef_json=None):

    doc = Document()

    root_el = doc.createElement("cluster")
    doc.appendChild(root_el)

    workspace_el = doc.createElement("workspace")
    root_el.appendChild(workspace_el)

    name_el = doc.createElement("name")
    workspace_el.appendChild(name_el)
    name_el_text = doc.createTextNode(name)
    name_el.appendChild(name_el_text)

    image_el = doc.createElement("image")
    workspace_el.appendChild(image_el)
    image_el_text = doc.createTextNode(image)
    image_el.appendChild(image_el_text)

    quantity_el = doc.createElement("quantity")
    workspace_el.appendChild(quantity_el)
    quantity_el_text = doc.createTextNode(str(quantity))
    quantity_el.appendChild(quantity_el_text)

    nic_el = doc.createElement("nic")
    nic_el.setAttribute("wantlogin", wantlogin)
    workspace_el.appendChild(nic_el)
    nic_el_text = doc.createTextNode(nic)
    nic_el.appendChild(nic_el_text)

    ctx_el = doc.createElement("ctx")
    workspace_el.appendChild(ctx_el)

    provides_el = doc.createElement("provides")
    ctx_el.appendChild(provides_el)

    provides_identity_el = doc.createElement("identity")
    provides_el.appendChild(provides_identity_el)

    requires_el = doc.createElement("requires")
    ctx_el.appendChild(requires_el)

    requires_identity_el = doc.createElement("identity")
    requires_el.appendChild(requires_identity_el)

    if chef_json:
        chef_config_string = json.dumps(chef_json)
        data_el = doc.createElement("data")
        data_el.setAttribute("name", "dt-chef-solo")
        requires_el.appendChild(data_el)
        cdata = doc.createCDATASection(chef_config_string)
        data_el.appendChild(cdata)

    return doc.toxml()
开发者ID:oldpatricka,项目名称:epu,代码行数:58,代码来源:core.py

示例7: GMap

# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import createCDATASection [as 别名]
class GMap(object):
    """
    Creates a KML file for Google Maps or Google Earth
    Usage: 
        
        m = GMap()
        m.add_placemark(lon=39, lat=39, title="Sample Placemark", desc="A longer description for the placemark. It can include <b>HTML</b>")
        print m.renderKML()
    """
    
    def __init__(self):
        self.doc = Document()
        self.kml = self.doc.createElement("kml")
        self.kml.setAttribute("http://www.opengis.net/kml/2.2")
        self.doc.appendChild(self.kml)
            
    def add_placemark(self, lon, lat, alt=2, title="Default", desc="",  show=1):
        # create <Placemark>
        placemark = self.doc.createElement("Placemark")
        self.kml.appendChild(placemark)
        
        
        # create <name> 
        name = self.doc.createElement("name")
        placemark.appendChild(name)
        name.appendChild( self.doc.createTextNode(title) )
        
        # create <visibility> 
        visibility = self.doc.createElement("visibility")
        placemark.appendChild(visibility)
        visibility.appendChild( self.doc.createTextNode("1") )
        
        # create <description>
        description = self.doc.createElement("description")
        placemark.appendChild(description)
        description.appendChild( self.doc.createCDATASection(desc) )

        # create <Point>
        point = self.doc.createElement("Point")
        placemark.appendChild(point)

        # create <coordinates>
        coordinates = self.doc.createElement("coordinates")
        point.appendChild(coordinates)
        coordinates.appendChild( self.doc.createTextNode( "%s,%s,%s" % ( lon , lat, alt)))

    def renderKML(self):
        return self.doc.toxml()
开发者ID:huyng,项目名称:pygmap,代码行数:50,代码来源:__init__.py

示例8: construct_feed

# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import createCDATASection [as 别名]
def construct_feed(reddit_items, feed_info):
    doc = Document()

    full_rss = doc.createElement('rss')
    full_rss.setAttribute('version', '2.0')

    channel = doc.createElement('channel')
    full_rss.appendChild(channel)

    title = doc.createElement('title')
    title.appendChild(doc.createTextNode(feed_info['title']))
    channel.appendChild(title)

    link = doc.createElement('link')
    link.appendChild(doc.createTextNode(feed_info['link']))
    channel.appendChild(link)

    description = doc.createElement('description')
    description.appendChild(doc.createTextNode(feed_info['description']))
    channel.appendChild(description)

    for i in reddit_items:
        item = doc.createElement('item')
        title = doc.createElement('title')
        title.appendChild(doc.createTextNode(i['ref_title']))

        link = doc.createElement('link')
        link.appendChild(doc.createTextNode(i['ref_link']))

        guid = doc.createElement('guid')
        guid.appendChild(doc.createTextNode(i['link']))

        description = doc.createElement('description')
        description.appendChild(doc.createCDATASection(i['content']))

        item.appendChild(title)
        item.appendChild(link)
        item.appendChild(guid)
        item.appendChild(description)

        channel.appendChild(item)

    doc.appendChild(full_rss)
    return doc.toxml()
开发者ID:hewigovens,项目名称:reddit-fun,代码行数:46,代码来源:index.py

示例9: open

# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import createCDATASection [as 别名]
doc=Document()
wordbook=doc.createElement('wordbook')
match=re.compile(u'(\d+)\.(.*?)([\u4e00-\u9fa5].*)')
with open('d:\\a.txt','r') as myfile:
    content=myfile.readlines()
    for  line in content:
        # print line
        item=doc.createElement('item')
        word=doc.createElement('word')
        trans=doc.createElement('trans')
        phonetic=doc.createElement('phonetic')
        tags=doc.createElement('tags')
        progress=doc.createElement('progress')
        
        matches=match.findall(line.decode())
        word.appendChild(doc.createCDATASection(matches[0][1]))
        trans.appendChild(doc.createCDATASection(matches[0][2]))
        progress.appendChild(doc.createTextNode('0'))
        phonetic.appendChild(doc.createTextNode(''))
        tags.appendChild(doc.createTextNode(''))
        item.appendChild(word)
        item.appendChild(trans)
        item.appendChild(phonetic)
        item.appendChild(tags)
        item.appendChild(progress)
        wordbook.appendChild(item)
    doc.appendChild(wordbook)
objxml=open('d:\\word.xml','w')
objxml.write(doc.toprettyxml(indent="  "))
objxml.close()
    
开发者ID:yongli-dang,项目名称:test,代码行数:32,代码来源:test1.py

示例10: CustomXMLBuilder

# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import createCDATASection [as 别名]
class CustomXMLBuilder(object):
    """
    This class builds the XML used to describe songs.
    """
    log.info(u'CustomXMLBuilder Loaded')

    def __init__(self):
        """
        Set up the custom builder.
        """
        # Create the minidom document
        self.custom_xml = Document()
        self.new_document()
        self.add_lyrics_to_song()

    def new_document(self):
        """
        Create a new custom XML document.
        """
        # Create the <song> base element
        self.song = self.custom_xml.createElement(u'song')
        self.custom_xml.appendChild(self.song)
        self.song.setAttribute(u'version', u'1.0')

    def add_lyrics_to_song(self):
        """
        Set up and add a ``<lyrics>`` tag which contains the lyrics of the
        custom item.
        """
        # Create the main <lyrics> element
        self.lyrics = self.custom_xml.createElement(u'lyrics')
        self.lyrics.setAttribute(u'language', u'en')
        self.song.appendChild(self.lyrics)

    def add_verse_to_lyrics(self, verse_type, number, content):
        """
        Add a verse to the ``<lyrics>`` tag.

        ``verse_type``
            A string denoting the type of verse. Possible values are "Chorus",
            "Verse", "Bridge", and "Custom".

        ``number``
            An integer denoting the number of the item, for example: verse 1.

        ``content``
            The actual text of the verse to be stored.
        """
        verse = self.custom_xml.createElement(u'verse')
        verse.setAttribute(u'type', verse_type)
        verse.setAttribute(u'label', number)
        self.lyrics.appendChild(verse)
        # add data as a CDATA section to protect the XML from special chars
        cds = self.custom_xml.createCDATASection(content)
        verse.appendChild(cds)

    def _dump_xml(self):
        """
        Debugging aid to dump XML so that we can see what we have.
        """
        return self.custom_xml.toprettyxml(indent=u'  ')

    def extract_xml(self):
        """
        Extract our newly created XML custom.
        """
        return self.custom_xml.toxml(u'utf-8')
开发者ID:marmyshev,项目名称:transitions,代码行数:69,代码来源:customxmlhandler.py

示例11: runxssdetect

# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import createCDATASection [as 别名]

#.........这里部分代码省略.........
                            self.outputxss.setColumnCount(7)
                            stime=QtGui.QTableWidgetItem(c.info()['total-time'])
                            sheader_size=QtGui.QTableWidgetItem(c.info()['header-size'])
                            sreq_size=QtGui.QTableWidgetItem(c.info()['request-size'])
                            scontent_type=QtGui.QTableWidgetItem(c.info()['content-type'])
                            
                            shtime=QtGui.QTableWidgetItem("Total-time")
                            shheader=QtGui.QTableWidgetItem("Header-size")
                            shreq_size=QtGui.QTableWidgetItem("Request-size")
                            shcontent_type=QtGui.QTableWidgetItem("Content-type")
                            
                            self.outputxss.setHorizontalHeaderItem(3,shtime)
                            self.outputxss.setHorizontalHeaderItem(4,shheader)
                            self.outputxss.setHorizontalHeaderItem(5,shreq_size)
                            self.outputxss.setHorizontalHeaderItem(6,shcontent_type)
                            
                            self.outputxss.setItem(i,3,stime)
                            self.outputxss.setItem(i,4,sheader_size)
                            self.outputxss.setItem(i,5,sreq_size)
                            self.outputxss.setItem(i,6,scontent_type)
                            
                    sresult=QtGui.QTableWidgetItem("Not injected")
                    self.outputxss.setItem(i,2,sresult)
                self.outputxss.resizeColumnsToContents()        
                i=i+1
                c.close()

                val=self.resultprogressbar.value()+progress_param2_pre
                self.resultprogressbar.setValue(val)
        
        ftimeS=time.gmtime().tm_sec
        ftimeM=time.gmtime().tm_min
        ftimeT=(ftimeM*60)+ftimeS
        if self.fullreportflag:
            f1=open(self.dpath+"/fullreport.txt","w")
            f1.write("XSS Alert\n")
            f1.write("\[email protected]  "+self.author_name)
            f1.write("\[email protected]  "+self.author_email)
            f1.write("\[email protected]  "+str(datetime.datetime.now())+"\n")
            for i in hash_found:
                f1.write("\n\[email protected] "+i[2])
                f1.write("\[email protected]_url "+i[0])
                f1.write("\[email protected] "+i[1])
            for i in hash_notfound:
                f1.write("\n\[email protected] "+i[2])
                f1.write("\[email protected]_url "+i[0])
                f1.write("\[email protected] "+i[1])
            f1.close()
        if self.xmlfileflag:
            dom=Document()
            x=dom.createElement("xssalert")
            dom.appendChild(x)
            fout=open(self.dpath+"/"+self.xmlfilename,"w")
            if len(hash_found)>0:
                    for line in hash_found:            
                        xa=dom.createElement("xssalertresult")
                        x.appendChild(xa)
                        ul=dom.createElement("targeturl")
                        xa.appendChild(ul)
                        ultest=dom.createTextNode(line[2])
                        ul.appendChild(ultest)
                        aul=dom.createElement("attackurl")
                        xa.appendChild(aul)
                        aultext=dom.createCDATASection(line[0])
                        aul.appendChild(aultext)
                        brw=dom.createElement("http-code")
                        xa.appendChild(brw)
                        brwtext=dom.createTextNode(line[1])
                        brw.appendChild(brwtext)
                        
                    fout.write(dom.toprettyxml(indent="  "))
                    fout.close()
            else:
                    xa=dom.createElement("xssalertresult")
                    x.appendChild(xa)
                    aul=dom.createElement("notfound")
                    xa.appendChild(aul)
                    aultext=dom.createTextNode("Not found any attack vector")
                    aul.appendChild(aultext)
                    fout.write(dom.toprettyxml(indent="  "))
                    fout.close()    
        i=0
        self.outputsuccessfull_vectors.setRowCount(len(hash_found))
        if (len(hash_found)>0):
                for line in hash_found:
                    surl=QtGui.QTableWidgetItem(line[0])
                    self.outputsuccessfull_vectors.setItem(i,0,surl)
                    i=i+1
        
        self.resultprogressbar.setValue(100)
        
        global finalUrl
        finalUrl=openbrowser
        
        self.total_vectors.setText(""+str(len(hash_found)+len(hash_notfound)))
        self.successfull_vectors.setText(""+str(len(hash_found)))
        self.failed_vectors.setText(""+str(len(hash_notfound)))
        self.total_time.setText(""+str(ftimeT-initimeT)+" S")
        if len(hash_found)>0:
            self.BrowserButton.setEnabled(True)
开发者ID:arjunjain,项目名称:xssalert,代码行数:104,代码来源:display.py

示例12: XMLReportGenerator

# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import createCDATASection [as 别名]
class XMLReportGenerator(ReportGenerator):
    """
    This class generates a report with the method printToFile(fileName) which contains
    the information of all the vulnerabilities notified to this object through the 
    method logVulnerability(vulnerabilityTypeName,level,url,parameter,info).
    The format of the file is XML and it has the following structure:
    <report type="security">
        <generatedBy id="WSP 1.0"/>
            <bugTypeList>
                <bugType name="SQL Injection">
                    <bugList/>

    <report>
        <vulnerabilityTypeList>
            <vulnerabilityType name="SQL Injection">
                <vulnerabilityList>
                    <vulnerability level="3">
                        <url>http://www.a.com</url>
                        <parameters>id=23</parameters>
                        <info>SQL Injection</info>
                    </vulnerability>
                </vulnerabilityList>
            </vulnerablityType>
        </vulnerabilityTypeList>
    </report>
    """

    __xmlDoc = None
    __vulnerabilityTypeList = None

    def __init__(self):
        self.__xmlDoc = Document()
        report = self.__addReport()
        generated = self.__xmlDoc.createElement("generatedBy")
        generated.setAttribute("id", WSP_VERSION);
        report.appendChild(generated)
        self.__vulnerabilityTypeList = self.__xmlDoc.createElement("bugTypeList")
        report.appendChild(self.__vulnerabilityTypeList)

    def __addReport(self):
        report = self.__xmlDoc.createElement("report")
        report.setAttribute("type", "security")
        self.__xmlDoc.appendChild(report)
        return report

    def __addToVulnerabilityTypeList(self, vulnerabilityType):
        self.__vulnerabilityTypeList.appendChild(vulnerabilityType)

    def addVulnerabilityType(self, name, description="", solution="", references={}):
        """
        This method adds a vulnerability type, it can be invoked to include in the
        report the type. 
        The types are not stored previously, they are added when the method 
        logVulnerability(vulnerabilityTypeName,level,url,parameter,info) is invoked
        and if there is no vulnerabilty of a type, this type will not be presented
        in the report
        """

        vulnerabilityType = self.__xmlDoc.createElement("bugType")
        vulnerabilityType.setAttribute("name", name)
        vulnerabilityType.appendChild(self.__xmlDoc.createElement("bugList"))
        self.__addToVulnerabilityTypeList(vulnerabilityType)
        if description != "":
            descriptionNode = self.__xmlDoc.createElement("description")
            descriptionNode.appendChild(self.__xmlDoc.createCDATASection(description))
            vulnerabilityType.appendChild(descriptionNode)
        if solution != "":
            solutionNode = self.__xmlDoc.createElement("solution")
            solutionNode.appendChild(self.__xmlDoc.createCDATASection(solution))
            vulnerabilityType.appendChild(solutionNode)
        if references != "":
            referencesNode = self.__xmlDoc.createElement("references")
            for ref in references:
                referenceNode = self.__xmlDoc.createElement("reference")
                titleNode = self.__xmlDoc.createElement("title")
                urlNode = self.__xmlDoc.createElement("url")
                titleNode.appendChild(self.__xmlDoc.createTextNode(ref))
                urlNode.appendChild(self.__xmlDoc.createTextNode(references[ref]))
                referenceNode.appendChild(titleNode)
                referenceNode.appendChild(urlNode)
                referencesNode.appendChild(referenceNode)
            vulnerabilityType.appendChild(referencesNode)
        return vulnerabilityType

    def __addToVulnerabilityList(self, vulnerabilityTypeName, vulnerability):
        vulnerabilityType = None
        for node in self.__vulnerabilityTypeList.childNodes:
            if node.nodeType == node.ELEMENT_NODE and node.getAttribute("name") == vulnerabilityTypeName:
                vulnerabilityType = node
                break
        if vulnerabilityType == None:
            vulnerabilityType = self.addVulnerabilityType(vulnerabilityTypeName)
        vulnerabilityType.childNodes[0].appendChild(vulnerability)

    def logVulnerability(self, vulnerabilityTypeName, level, url, parameter, info):
        """
        Store the information about the vulnerability to be printed later.
        The method printToFile(fileName) can be used to save in a file the
        vulnerabilities notified through the current method.
        """
#.........这里部分代码省略.........
开发者ID:akalex,项目名称:DevProject,代码行数:103,代码来源:xmlreportgenerator.py

示例13: len

# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import createCDATASection [as 别名]
for car in entry:
    alist.append(car['brand']) #Make all the brands to a list
print len(set(alist)) #Set() removes duplicates

#Cumulative number of doors for all cars
doors = 0
for car in entry:
    doors = doors + car['nb_doors']
print doors

#Print car description of the 4th car of the list
print entry[3]['name'] + " " + entry[3]['brand'] + " " + "(" + str(entry[3]['nb_doors']) + ")"

#Create a DOM document with all cars and print it
doc = Document()
cars = doc.createElement('cars')
doc.appendChild(cars)
for element in entry:
    car = doc.createElement('car')
    car.setAttribute('nb_doors', str((element['nb_doors'])))
    cars.appendChild(car)
    name = doc.createElement('name')
    name_content = doc.createCDATASection(element['name'])
    name.appendChild(name_content)
    car.appendChild(name)
    brand = doc.createElement('brand')
    brand_content = doc.createTextNode(element['brand'])
    brand.appendChild(brand_content)
    car.appendChild(brand)
print doc.toxml(encoding='utf-8')
开发者ID:Praylin,项目名称:holbertonschool-higher_level_programming,代码行数:32,代码来源:5-main.py

示例14: OpenVASReportGenerator

# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import createCDATASection [as 别名]

#.........这里部分代码省略.........
        report_infos.appendChild(scan_run_status)

        scan_start = self.__xmlDoc.createElement("scan_start")
        scan_start.appendChild(self.__xmlDoc.createTextNode(self.__infos["date"]))
        report_infos.appendChild(scan_start)

        results = self.__xmlDoc.createElement("results")
        results.setAttribute("start", "1")
        results.setAttribute("max", str(self.__vulnCount + self.__anomCount))

        # Loop on each flaw classification
        for flawType in self.__flawTypes:
            classification = ""
            flaw_dict = {}
            if flawType in self.__vulns:
                classification = "vulnerability"
                flaw_dict = self.__vulns
            elif flawType in self.__anomalies:
                classification = "anomaly"
                flaw_dict = self.__anomalies

            for flaw in flaw_dict[flawType]:
                result = self.__xmlDoc.createElement("result")
                result.setAttribute("id", str(uuid.uuid4()))

                subnet = self.__xmlDoc.createElement("subnet")
                subnet.appendChild(self.__xmlDoc.createTextNode(flaw["hostname"]))
                result.appendChild(subnet)

                host = self.__xmlDoc.createElement("host")
                host.appendChild(self.__xmlDoc.createTextNode(flaw["hostname"]))
                result.appendChild(host)

                port = self.__xmlDoc.createElement("port")
                port.appendChild(self.__xmlDoc.createTextNode(str(flaw["port"])))
                result.appendChild(port)

                nvt = self.__xmlDoc.createElement("nvt")
                nvt.setAttribute("oid", str(uuid.uuid4()))

                name = self.__xmlDoc.createElement("name")
                name.appendChild(self.__xmlDoc.createTextNode(flawType))
                nvt.appendChild(name)

                family = self.__xmlDoc.createElement("family")
                family.appendChild(self.__xmlDoc.createTextNode(classification))
                nvt.appendChild(family)

                cvss_base = self.__xmlDoc.createElement("cvss_base")
                cvss_base.appendChild(self.__xmlDoc.createTextNode("0.0"))
                nvt.appendChild(cvss_base)

                risk_factor = self.__xmlDoc.createElement("risk_factor")
                risk_factor.appendChild(self.__xmlDoc.createTextNode(str(flaw["level"])))
                nvt.appendChild(risk_factor)

                cve = self.__xmlDoc.createElement("cve")
                cve.appendChild(self.__xmlDoc.createTextNode(""))
                nvt.appendChild(cve)

                bid = self.__xmlDoc.createElement("bid")
                bid.appendChild(self.__xmlDoc.createTextNode(""))
                nvt.appendChild(bid)

                tags = self.__xmlDoc.createElement("tags")
                tags.appendChild(self.__xmlDoc.createTextNode(""))
                nvt.appendChild(tags)

                certs = self.__xmlDoc.createElement("certs")
                certs.appendChild(self.__xmlDoc.createTextNode(""))
                nvt.appendChild(certs)

                xref = self.__xmlDoc.createElement("xref")
                xref.appendChild(self.__xmlDoc.createTextNode("NOXREF"))
                nvt.appendChild(xref)

                result.appendChild(nvt)

                threat = self.__xmlDoc.createElement("threat")
                threat.appendChild(self.__xmlDoc.createTextNode(str(flaw["level"])))
                result.appendChild(threat)

                description = self.__xmlDoc.createElement("description")
                description.appendChild(self.__xmlDoc.createCDATASection(flaw["info"]))
                result.appendChild(description)

                original_threat = self.__xmlDoc.createElement("original_threat")
                original_threat.appendChild(self.__xmlDoc.createTextNode(str(flaw["level"])))
                result.appendChild(original_threat)

                results.appendChild(result)

        report_infos.appendChild(results)
        report.appendChild(report_infos)

        f = open(fileName, "w")
        try:
            f.write(self.__xmlDoc.toprettyxml(indent="    ", encoding="UTF-8"))
        finally:
            f.close()
开发者ID:AmesianX,项目名称:HackingStuff,代码行数:104,代码来源:openvasreportgenerator.py

示例15: Document

# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import createCDATASection [as 别名]
from xml.dom.minidom import Document
from car import Car
from json import loads

"""Setting the dom obj"""
doc = Document()
x_cars = doc.createElement('cars')
doc.appendChild(x_cars)

"""Opening the json file"""
with open('./7-main.json') as f:
    data = loads(f.read())

"""Iterating through each obj and adding them to the dom"""
for car in data:
    item = Car(car)
    c_xml = item.to_xml_node(doc)
    year = doc.createElement('year')
    year_value = doc.createTextNode('2015')
    year.appendChild(year_value)
    c_xml.appendChild(year)
    c_xml.setAttribute('weight', str(1000))
    brand = doc.createElement('brand')
    brand_value = doc.createCDATASection(u"\u00a9" + item.get_brand())
    brand.appendChild(brand_value)
    c_xml.replaceChild(brand, c_xml.getElementsByTagName('brand')[0])
    x_cars.appendChild(c_xml)

"""Printing the dom to xml"""
print doc.toxml(encoding='utf-8')
开发者ID:havk64,项目名称:holbertonschool-higher_level_programming,代码行数:32,代码来源:7-main.py


注:本文中的xml.dom.minidom.Document.createCDATASection方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。