コード例 #1
0
def _testElementReprAndStrUnicode():
    dom = Document()
    el = dom.appendChild(dom.createElement(u"abc"))
    string1 = repr(el)
    string2 = str(el)
    confirm(string1 == string2)
    dom.unlink()
コード例 #2
0
def _testElementReprAndStrUnicode():
    dom = Document()
    el = dom.appendChild(dom.createElement(u"abc"))
    string1 = repr(el)
    string2 = str(el)
    confirm(string1 == string2)
    dom.unlink()
コード例 #3
0
    def toDyf(self):
        doc = Document()
        ws = doc.createElement("Workspace")
        ws.setAttribute("Version", self.VERSION)
        ws.setAttribute("X", str(self.X))
        ws.setAttribute("Y", str(self.Y))
        ws.setAttribute("zoom", str(self.ZOOM))
        ws.setAttribute("Name", self.name)
        ws.setAttribute("Description", self.description)
        ws.setAttribute("ID", str(self.wsId))
        ws.setAttribute("Category", '.'.join(
            (self.category, self.subcategory)))
        doc.appendChild(ws)

        # add child objects
        for child in self.CHILDREN:
            elm = doc.createElement(child[0].upper() + child[1:])
            # get elements for child
            childs = getattr(self, child)
            if len(childs) == 0:
                ws.appendChild(elm)
            for ch in childs:
                # creat the child
                self.addChild(doc, ws, elm, ch)

        text = '\n'.join(doc.toprettyxml(indent="  ").split('\n')[1:])

        doc.unlink()

        return text.replace('&', '&')
コード例 #4
0
ファイル: MainView.py プロジェクト: phymucs/code_saturne
    def SaveState(self):
        """
        """
        newdoc = Document()

        root = newdoc.createElement('root')
        newdoc.appendChild(root)

        newnode = newdoc.createElement('timeRefresh')
        newnode.setAttribute("value", str(self.timeRefresh))
        root.appendChild(newnode)
        newnode = newdoc.createElement('subplotNumber')
        newnode.setAttribute("value", str(self.subplotNumber))
        root.appendChild(newnode)

        for (name, fle, status, subplot_id, probes_number) in self.fileList:
            newnode = newdoc.createElement('file')
            newnode.setAttribute("name", name)
            root.appendChild(newnode)

            for itt in self.listFileProbes[name]:
                node = newdoc.createElement('probe')
                node.setAttribute("id", str(itt.index))
                node.setAttribute("name", itt.name)
                node.setAttribute("status", itt.status)
                node.setAttribute("subplot_id", str(itt.subplot_id))
                newnode.appendChild(node)

        name = os.path.join(self.caseName, '.trackcvg.state')
        ficIn = open(name, 'w')

        newdoc.writexml(ficIn, indent="  ", addindent="  ", newl='\n')

        newdoc.unlink()
        ficIn.close()
コード例 #5
0
ファイル: manager.py プロジェクト: f4b10/X4GA
    def StoreXml(self, dValue):
        try:
            cBasePath=self.GetUpdatePath()
            now    = datetime.datetime.utcnow()
            nowFile='%s-%s' % (now.strftime('%Y%m%d-%H%M%S'), '%04d' % (now.microsecond /1000))
            nowXml ='%s:%s' % (now.strftime('%Y%m%d-%H:%M:%S'), '%04d' % (now.microsecond /1000))
            doc=Document()
            root = doc.createElement("dbUpdate")
            for k in ['table', 'operation']:
                root.setAttribute( k, dValue[k] )
            root.setAttribute( 'datetime', '%s' % nowXml )
            doc.appendChild(root)

            root.appendChild(self.CreateVersionNode(doc))
            root.appendChild(self.CreateRecordNode(doc, dValue))

            pathName=os.path.join(cBasePath, '%s' % nowFile)
            self._mkdir_recursive(pathName)
            fileName=os.path.join(pathName, '%s.xml' % nowFile )
            doc.writexml( open(fileName, 'w'),
                          indent="  ",
                          addindent="  ",
                          newl='\n')
            doc.unlink()
            lEsito=True
        except:
            lEsito=False
        return lEsito
コード例 #6
0
def testAttributeRepr():
    dom = Document()
    el = dom.appendChild(dom.createElement(u"abc"))
    node = el.setAttribute("abc", "def")
    confirm(str(node) == repr(node))
    dom.unlink()
    confirm(len(Node.allnodes) == 0)
コード例 #7
0
ファイル: addon.py プロジェクト: kuggaa/Kodi-1
def addToFavorite(game):
    doc = None
    root = None

    if (not os.path.isfile(FAVOURITES_PATH)):
        doc = Document()
        root = doc.createElement("favourites")
        doc.appendChild(root)
    else:
        doc = parse(FAVOURITES_PATH)
        root = doc.documentElement

    favNode = doc.createElement("favourite")
    root.appendChild(favNode)

    favNode.setAttribute("name", game.title)
    favNode.setAttribute("thumb", game.thumbImage)

    url = getGameLaunchUrlAction(game)

    textNode = doc.createTextNode(url)
    favNode.appendChild(textNode)

    doc.writexml(open(FAVOURITES_PATH, 'w'))

    doc.unlink()
コード例 #8
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()
コード例 #9
0
def testAttributeRepr():
    dom = Document()
    el = dom.appendChild(dom.createElement(u"abc"))
    node = el.setAttribute("abc", "def")
    confirm(str(node) == repr(node))
    dom.unlink()
    confirm(len(Node.allnodes) == 0)
コード例 #10
0
ファイル: test_minidom.py プロジェクト: zushilong003/jython3
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()
コード例 #11
0
ファイル: addon.py プロジェクト: Brainiarc7/Kodi
def addToFavorite(game):
    doc = None
    root = None

    if (not os.path.isfile(FAVOURITES_PATH)):            
        doc = Document()
        root = doc.createElement("favourites")
        doc.appendChild(root)
    else:
        doc = parse( FAVOURITES_PATH )
        root = doc.documentElement

    favNode = doc.createElement("favourite")
    root.appendChild(favNode)

    favNode.setAttribute( "name", game.title)
    favNode.setAttribute( "thumb", game.thumbImage)

    url = getGameLaunchUrlAction(game)

    textNode = doc.createTextNode(url)
    favNode.appendChild(textNode)
 
    doc.writexml(open(FAVOURITES_PATH, 'w'))
 
    doc.unlink()
コード例 #12
0
def writeDocument(sourcePath,targetPath,xmlFileName):

    if sourcePath == None or targetPath == None:
        return False

    ## Added May2016. warn user if capabilities are not correct, exit if not a valid layer
    if not dla.checkServiceCapabilities(sourcePath,False):
        return False
    if not dla.checkServiceCapabilities(targetPath,False):
        return False

    desc = arcpy.Describe(sourcePath)
    descT = arcpy.Describe(targetPath)

    xmlDoc = Document()
    root = xmlDoc.createElement('SourceTargetMatrix')
    xmlDoc.appendChild(root)
    root.setAttribute("version",'1.1')
    root.setAttribute("xmlns:esri",'http://www.esri.com')
    
    dataset = xmlDoc.createElement("Datasets")
    root.appendChild(dataset)
    prj = dla.getProject()
    setSourceTarget(dataset,xmlDoc,"Project",prj.filePath)
    setSourceTarget(dataset,xmlDoc,"Source",sourcePath)
    setSourceTarget(dataset,xmlDoc,"Target",targetPath)

    setSpatialReference(dataset,xmlDoc,desc,"Source")
    setSpatialReference(dataset,xmlDoc,descT,"Target")

    setSourceTarget(dataset,xmlDoc,"ReplaceBy","")

    fieldroot = xmlDoc.createElement("Fields")
    root.appendChild(fieldroot)

    fields = getFields(descT)
    sourceFields = getFields(desc)
    sourceNames = [field.name[field.name.rfind(".")+1:] for field in sourceFields]
    upperNames = [nm.upper() for nm in sourceNames]

    #try:
    for field in fields:

        fNode = xmlDoc.createElement("Field")
        fieldroot.appendChild(fNode)
        fieldName = field.name[field.name.rfind(".")+1:]
        matchSourceFields(xmlDoc,fNode,field,fieldName,sourceNames,upperNames)

    # write the source field values
    setSourceFields(root,xmlDoc,sourceFields)
    setTargetFields(root,xmlDoc,fields)
    # Should add a template section for value maps, maybe write domains...
    # could try to preset field mapping and domain mapping...

    # add data to the document
    writeDataSample(xmlDoc,root,sourceNames,sourcePath,10)
    # write it out
    xmlDoc.writexml( open(xmlFileName, 'wt', encoding='utf-8'),indent="  ",addindent="  ",newl='\n')
    xmlDoc.unlink()
コード例 #13
0
ファイル: base.py プロジェクト: rauljuarez/vxvCrawler
def build_xml_results_batch(results_batch,config):
    """ Takes a data structure containing the results of the searchs and builds an xml representation."""
    doc=Document()
    root=doc.createElement('search_results')
    root.setAttribute('guid',config.get('clientid','0000'))
    doc.appendChild(root)
    
    for result in results_batch:
        video=doc.createElement('video')
        video.setAttribute('search-id',str(result['search-id']))
        video.setAttribute('video-id',str(result['video-id']))
        video.setAttribute('source',result['source'])
        
        title=doc.createElement('title')
        title.appendChild(doc.createTextNode(result['title']))
        video.appendChild(title)
        
        desc=doc.createElement('description')
        if result['description']!=None:
            desc.appendChild(doc.createTextNode(result['description']))
        else:
            desc.appendChild(doc.createTextNode(''))
        video.appendChild(desc)

        cat=doc.createElement('category')
        if result['category']!=None:
            cat.appendChild(doc.createTextNode(result['category']))
        video.appendChild(cat)

        tags=doc.createElement('tags')
        if result['tags']!=None:
            tags.appendChild(doc.createTextNode(result['tags']))
        video.appendChild(tags)

        purl=doc.createElement('page_url')
        purl.appendChild(doc.createTextNode(result['page_url']))
        video.appendChild(purl)
        
        if result['lq_url']!=None:
            lq_url=doc.createElement('lq_url')
            lq_url.appendChild(doc.createTextNode(result['lq_url']))
            video.appendChild(lq_url)

        if result['hq_url']!=None:
            hq_url=doc.createElement('hq_url')
            hq_url.appendChild(doc.createTextNode(result['hq_url']))
            video.appendChild(hq_url)
        
        if result['hd_url']!=None:
            hd_url=doc.createElement('hd_url')
            hd_url.appendChild(doc.createTextNode(result['hd_url']))
            video.appendChild(hd_url)

        root.appendChild(video)
        
    xml_str=doc.toxml()
    doc.unlink()
    sanitized_xml_data=''.join([c for c in xml_str if ord(c)<128])
    return sanitized_xml_data 
コード例 #14
0
ファイル: find_cycles.py プロジェクト: jasonivey/scripts
class CycleFinder:
    "Object which controlls all the aspects of finding cycles in source files."
    def __init__(self, dir):
        self.mDirectory = dir
        self.mFiles = []
        self.mXmlDocument = Document()
        self.mXml = None
        
    def Execute(self, filename):
        extensions = ['.inl', '.h', '.hpp', '.c', '.cc', '.cpp']
        files = []
        for root, dirs, f in os.walk( self.mDirectory ):
            paths = []
            searched = False
            for file in f:
                if not searched:
                    searched = True
                    paths = GetIncludePaths(root)
    
                extension = os.path.splitext(file)[1].lower()
                if extension in extensions:
                    name = os.path.join( root, file ).lower();
                    file = CppFile(name, paths, self)
                    file.ParseIncludes()
                    self.AddFile(file)

        self.mXml = self.mXmlDocument.createElement( "CycleFinder" )
        
        for file in self.mFiles:
            if os.path.basename(file.mName) == 'bytes.inl':
                print('.')
            print(('Processing %s.' % os.path.basename(file.mName)))
            file.AnalyzeDependencies()
        
        self.mXmlDocument.appendChild( self.mXml )
        file = open( filename, 'w' )
        file.write( self.mXmlDocument.toprettyxml() )
        self.mXmlDocument.unlink()
        file.close()
        

    def AddFile(self, file):
        if file not in self.mFiles:
            self.mFiles.append(file)
    
    def GetHeaderFile(self, name):
        retfile = None
        file = CppFile(name, [], self)
        if file not in self.mFiles:
            print(('Unable to find existing file %s.' % name))
        else:
            retfile = self.mFiles[self.mFiles.index(file)]
        return retfile
    
    def __str__(self):
        str = 'Parsing Files In %s' % self.mDirectory
        for file in self.mFiles:
            str += '%s' % file
        return str
コード例 #15
0
def writeFile(fileName, persons):
    
    doc = Document()
     
    root = doc.createElement("PersonList")
    doc.appendChild(root)

    id = 0;
         
    for person in persons:

        personList = doc.createElement("Person")
        personList.setAttribute("id", str(id))
        id += 1
        root.appendChild(personList)
        
        print person
        # Create Element
        tempChild = doc.createElement("name")
        personList.appendChild(tempChild)
     
        # Write Text
        nodeText = doc.createTextNode(person.name)
        tempChild.appendChild(nodeText)

        # Create Element
        tempChild = doc.createElement("gender")
        personList.appendChild(tempChild)
     
        # Write Text
        nodeText = doc.createTextNode(person.gender)
        tempChild.appendChild(nodeText)

        # Create Element
        tempChild = doc.createElement("phone")
        personList.appendChild(tempChild)
     
        # Write Text
        nodeText = doc.createTextNode(person.phone)
        tempChild.appendChild(nodeText)

        # Create Element
        tempChild = doc.createElement("email")
        personList.appendChild(tempChild)
     
        # Write Text
        nodeText = doc.createTextNode(person.email)
        tempChild.appendChild(nodeText)

    # Write File 
    doc.writexml( open((fileName+".xml"), 'w'),
                   indent="  ",
                   addindent="  ",
                   newl='\n')
     
    doc.unlink()

    print "ÀÉ®×¼g¤J§¹¦¨!"
コード例 #16
0
ファイル: test_minidom.py プロジェクト: Bail-jw/mediacomp-jes
def _testElementReprAndStrUnicodeNS():
    dom = Document()
    el = dom.appendChild(
        dom.createElementNS(u"http://www.slashdot.org", u"slash:abc"))
    string1 = repr(el)
    string2 = str(el)
    confirm(string1 == string2)
    confirm(string1.find("slash:abc") != -1)
    dom.unlink()
コード例 #17
0
ファイル: test_minidom.py プロジェクト: ShinyArceus1/ROS-Code
def _testElementReprAndStrUnicodeNS():
    dom = Document()
    el = dom.appendChild(
        dom.createElementNS(u"http://www.slashdot.org", u"slash:abc"))
    string1 = repr(el)
    string2 = str(el)
    confirm(string1 == string2)
    confirm(string1.find("slash:abc") != -1)
    dom.unlink()
コード例 #18
0
def testDeleteAttr():
    dom = Document()
    child = dom.appendChild(dom.createElement("abc"))

    confirm(len(child.attributes) == 0)
    child.setAttribute("def", "ghi")
    confirm(len(child.attributes) == 1)
    del child.attributes["def"]
    confirm(len(child.attributes) == 0)
    dom.unlink()
コード例 #19
0
def testRemoveAttr():
    dom = Document()
    child = dom.appendChild(dom.createElement("abc"))

    child.setAttribute("def", "ghi")
    confirm(len(child.attributes) == 1)
    child.removeAttribute("def")
    confirm(len(child.attributes) == 0)

    dom.unlink()
コード例 #20
0
def testRemoveAttributeNode():
    dom = Document()
    child = dom.appendChild(dom.createElement("foo"))
    child.setAttribute("spam", "jam")
    confirm(len(child.attributes) == 1)
    node = child.getAttributeNode("spam")
    child.removeAttributeNode(node)
    confirm(len(child.attributes) == 0)

    dom.unlink()
コード例 #21
0
def testRemoveAttr():
    dom = Document()
    child = dom.appendChild(dom.createElement("abc"))

    child.setAttribute("def", "ghi")
    confirm(len(child.attributes) == 1)
    child.removeAttribute("def")
    confirm(len(child.attributes) == 0)

    dom.unlink()
コード例 #22
0
def testDeleteAttr():
    dom = Document()
    child = dom.appendChild(dom.createElement("abc"))

    confirm(len(child.attributes) == 0)
    child.setAttribute("def", "ghi")
    confirm(len(child.attributes) == 1)
    del child.attributes["def"]
    confirm(len(child.attributes) == 0)
    dom.unlink()
コード例 #23
0
def testRemoveAttributeNode():
    dom = Document()
    child = dom.appendChild(dom.createElement("foo"))
    child.setAttribute("spam", "jam")
    confirm(len(child.attributes) == 1)
    node = child.getAttributeNode("spam")
    child.removeAttributeNode(node)
    confirm(len(child.attributes) == 0)

    dom.unlink()
コード例 #24
0
def testRemoveAttrNS():
    dom = Document()
    child = dom.appendChild(
        dom.createElementNS("http://www.python.org", "python:abc"))
    child.setAttributeNS("http://www.w3.org", "xmlns:python",
                         "http://www.python.org")
    child.setAttributeNS("http://www.python.org", "python:abcattr", "foo")
    confirm(len(child.attributes) == 2)
    child.removeAttributeNS("http://www.python.org", "abcattr")
    confirm(len(child.attributes) == 1)

    dom.unlink()
コード例 #25
0
    def save_xml_doc(self):
        material_dict = self.materials.material_dict
        doc = Document()
        filename = self.parent.filename
        materials_xml = doc.createElement("materials")
        doc.appendChild(materials_xml)
        for name, material in material_dict.items():
            material_xml = doc.createElement("material")
            materials_xml.appendChild(material_xml)
            name_xml = doc.createElement("name")
            material_xml.appendChild(name_xml)
            name_text = doc.createTextNode(name)
            name_xml.appendChild(name_text)
            surface_color_xml = doc.createElement( "surface_color")
            material_xml.appendChild(surface_color_xml)
            red_xml = doc.createElement("red")
            surface_color_xml.appendChild(red_xml)
            green_xml = doc.createElement("green")
            surface_color_xml.appendChild(green_xml)
            blue_xml = doc.createElement("blue")
            surface_color_xml.appendChild(blue_xml)
            red_text = doc.createTextNode(str(material.get_surface_colour()[0]))
            red_xml.appendChild(red_text)
            green_text = doc.createTextNode(str(material.get_surface_colour()[1]))
            green_xml.appendChild(green_text)
            blue_text = doc.createTextNode(str(material.get_surface_colour()[2]))
            blue_xml.appendChild(blue_text)
            transparency_xml = doc.createElement("transparency")
            material_xml.appendChild(transparency_xml)
            transparency_text = doc.createTextNode(str(material.get_transparency()))
            transparency_xml.appendChild(transparency_text)
            reflectance_method_xml = doc.createElement("reflectance_method")
            material_xml.appendChild(reflectance_method_xml)
            reflectance_method_text = doc.createTextNode(str(material.get_reflectance_method()))
            reflectance_method_xml.appendChild(reflectance_method_text)
            reflectance_xml = doc.createElement("reflectance")
            material_xml.appendChild(reflectance_xml)
            reflectance_text = doc.createTextNode(str(material.get_reflectance()))
            reflectance_xml.appendChild(reflectance_text)
            slip_coefficient_xml = doc.createElement("slip_coefficient")
            material_xml.appendChild(slip_coefficient_xml)
            slip_coefficient_text = doc.createTextNode(str(material.get_slip_coefficient()))
            slip_coefficient_xml.appendChild(slip_coefficient_text)
            imperviousness_xml = doc.createElement("imperviousness")
            material_xml.appendChild(imperviousness_xml)
            imperviousness_text = doc.createTextNode(str(material.get_imperviousness()))
            imperviousness_xml.appendChild(imperviousness_text)

        doc.writexml( open(filename+".xml", 'w'),
                          indent="  ",
                          addindent="  ",
                          newl='\n')
        doc.unlink()
コード例 #26
0
def testRemoveAttrNS():
    dom = Document()
    child = dom.appendChild(
            dom.createElementNS("http://www.python.org", "python:abc"))
    child.setAttributeNS("http://www.w3.org", "xmlns:python",
                                            "http://www.python.org")
    child.setAttributeNS("http://www.python.org", "python:abcattr", "foo")
    confirm(len(child.attributes) == 2)
    child.removeAttributeNS("http://www.python.org", "abcattr")
    confirm(len(child.attributes) == 1)

    dom.unlink()
コード例 #27
0
def testNamedNodeMapSetItem():
    dom = Document()
    elem = dom.createElement('element')
    attrs = elem.attributes
    attrs["foo"] = "bar"
    a = attrs.item(0)
    confirm(a.ownerDocument is dom,
            "NamedNodeMap.__setitem__() sets ownerDocument")
    confirm(a.ownerElement is elem,
            "NamedNodeMap.__setitem__() sets ownerElement")
    confirm(a.value == "bar", "NamedNodeMap.__setitem__() sets value")
    confirm(a.nodeValue == "bar", "NamedNodeMap.__setitem__() sets nodeValue")
    elem.unlink()
    dom.unlink()
コード例 #28
0
	def saveFile(self, sourceModel, filename):
		saveResult = None
		search = SettingStruct.DeepSearchSettingTree(sourceModel)
		doc = Document()
		for childTreeEntryTupel in search.getElementGenerator():
			settings = childTreeEntryTupel[1].data(1).getDependSettings()
			for setting in settings:
				fileInfo = setting.fileInformation
				element = doc
				for path in fileInfo.xmlpath:
					found = False
					for node in reversed(element.childNodes):
						if node.nodeType == node.ELEMENT_NODE:
							if node.tagName == path:
								if not path is fileInfo.xmlpath[-1]:
									found = True
									element = node
								else:
									if fileInfo.attribute != "":
										if not node.hasAttribute(fileInfo.attribute):
											found = True
											element = node
									if len(node.childNodes) == 0:
										found = True
										element = node
								break
					if not found:
						newElement = doc.createElement(path)
						element.appendChild(newElement)
						element = newElement
				
				if fileInfo.attribute != "":
					element.setAttribute(fileInfo.attribute, setting.value)
				else:
					if setting.value != "":
						textNode = doc.createTextNode(setting.value)
						element.appendChild(textNode)
		prettyXML = doc.toprettyxml(indent="  ", newl='\n', encoding="UTF-8")
		try:
			file = QFile(filename)
			if file.open(QIODevice.WriteOnly):
				file.write(prettyXML)
				file.close()
			else:
				saveResult = ""
		except IOError as e:
			saveResult = str(e)
		finally:
			doc.unlink()
			return saveResult
コード例 #29
0
ファイル: orngDoc.py プロジェクト: electricFeel/BeatKeeperHRM
    def save(self, filename=None):
        if filename is None:
            filename = os.path.join(self.schemaPath, self.schemaName)
            
        # create xml document
        doc = Document()
        schema = doc.createElement("schema")
        widgets = doc.createElement("widgets")
        lines = doc.createElement("channels")
        settings = doc.createElement("settings")
        doc.appendChild(schema)
        schema.appendChild(widgets)
        schema.appendChild(lines)
        schema.appendChild(settings)
        settingsDict = {}

        #save widgets
        for widget in self.widgets:
            temp = doc.createElement("widget")
            temp.setAttribute("xPos", str(int(widget.x())) )
            temp.setAttribute("yPos", str(int(widget.y())) )
            temp.setAttribute("caption", widget.caption)
            temp.setAttribute("widgetName", widget.widgetInfo.fileName)
            settingsDict[widget.caption] = widget.instance.saveSettingsStr()
            widgets.appendChild(temp)

        #save connections
        for line in self.lines:
            temp = doc.createElement("channel")
            temp.setAttribute("outWidgetCaption", line.outWidget.caption)
            temp.setAttribute("inWidgetCaption", line.inWidget.caption)
            temp.setAttribute("enabled", str(line.getEnabled()))
            temp.setAttribute("signals", str(line.getSignals()))
            lines.appendChild(temp)

        settings.setAttribute("settingsDictionary", str(settingsDict))

        xmlText = doc.toprettyxml()

        file = open(filename, "wt")
        file.write(xmlText)
        file.close()
        doc.unlink()

        if os.path.splitext(filename)[1].lower() == ".ows":
            (self.schemaPath, self.schemaName) = os.path.split(filename)
            self.canvasDlg.settings["saveSchemaDir"] = self.schemaPath
            self.canvasDlg.addToRecentMenu(filename)
            self.canvasDlg.setCaption(self.schemaName)
コード例 #30
0
    def save(self, filename=None):
        if filename is None:
            filename = os.path.join(self.schemaPath, self.schemaName)

        # create xml document
        doc = Document()
        schema = doc.createElement("schema")
        widgets = doc.createElement("widgets")
        lines = doc.createElement("channels")
        settings = doc.createElement("settings")
        doc.appendChild(schema)
        schema.appendChild(widgets)
        schema.appendChild(lines)
        schema.appendChild(settings)
        settingsDict = {}

        #save widgets
        for widget in self.widgets:
            temp = doc.createElement("widget")
            temp.setAttribute("xPos", str(int(widget.x())))
            temp.setAttribute("yPos", str(int(widget.y())))
            temp.setAttribute("caption", widget.caption)
            temp.setAttribute("widgetName", widget.widgetInfo.fileName)
            settingsDict[widget.caption] = widget.instance.saveSettingsStr()
            widgets.appendChild(temp)

        #save connections
        for line in self.lines:
            temp = doc.createElement("channel")
            temp.setAttribute("outWidgetCaption", line.outWidget.caption)
            temp.setAttribute("inWidgetCaption", line.inWidget.caption)
            temp.setAttribute("enabled", str(line.getEnabled()))
            temp.setAttribute("signals", str(line.getSignals()))
            lines.appendChild(temp)

        settings.setAttribute("settingsDictionary", str(settingsDict))

        xmlText = doc.toprettyxml()

        file = open(filename, "wt")
        file.write(xmlText)
        file.close()
        doc.unlink()

        if os.path.splitext(filename)[1].lower() == ".ows":
            (self.schemaPath, self.schemaName) = os.path.split(filename)
            self.canvasDlg.settings["saveSchemaDir"] = self.schemaPath
            self.canvasDlg.addToRecentMenu(filename)
            self.canvasDlg.setCaption(self.schemaName)
コード例 #31
0
ファイル: osm.py プロジェクト: OpenSeaMap/lol_utils
    def Write(self, filename):
        doc = Document()

        osm = doc.createElement("osm")
        osm.setAttribute("version", '0.6')

        for seamark in self.SeaMarkList:
            retv = seamark.getElementsByTagName('tag')
            if (len(retv) > 0):
                osm.appendChild(seamark)

        doc.appendChild(osm)

        doc.writexml(open(filename, 'w'), indent="  ", addindent="  ")
        doc.unlink()
コード例 #32
0
ファイル: satxml.py プロジェクト: audi06/DemonEditor
def write_satellites(satellites, data_path):
    """ Creation satellites.xml file """
    doc = Document()
    comment = doc.createComment(__COMMENT)
    doc.appendChild(comment)
    root = doc.createElement("satellites")
    doc.appendChild(root)

    for sat in satellites:
        #    Create Element
        sat_child = doc.createElement("sat")
        sat_child.setAttribute("name", sat.name)
        sat_child.setAttribute("flags", sat.flags)
        sat_child.setAttribute("position", sat.position)

        for tr in sat.transponders:
            transponder_child = doc.createElement("transponder")
            transponder_child.setAttribute("frequency", tr.frequency)
            transponder_child.setAttribute("symbol_rate", tr.symbol_rate)
            transponder_child.setAttribute(
                "polarization", get_key_by_value(POLARIZATION,
                                                 tr.polarization))
            transponder_child.setAttribute(
                "fec_inner",
                get_key_by_value(FEC, tr.fec_inner) or "0")
            transponder_child.setAttribute(
                "system",
                get_key_by_value(SYSTEM, tr.system) or "0")
            transponder_child.setAttribute(
                "modulation",
                get_key_by_value(MODULATION, tr.modulation) or "0")
            if tr.pls_mode:
                transponder_child.setAttribute("pls_mode", tr.pls_mode)
            if tr.pls_code:
                transponder_child.setAttribute("pls_code", tr.pls_code)
            if tr.is_id:
                transponder_child.setAttribute("is_id", tr.is_id)
            if tr.t2mi_plp_id:
                transponder_child.setAttribute("t2mi_plp_id", tr.t2mi_plp_id)
            sat_child.appendChild(transponder_child)
        root.appendChild(sat_child)
    doc.writexml(
        open(data_path, "w"),
        # indent="",
        addindent="    ",
        newl='\n',
        encoding="iso-8859-1")
    doc.unlink()
コード例 #33
0
ファイル: test_minidom.py プロジェクト: Bail-jw/mediacomp-jes
def testNamedNodeMapSetItem():
    dom = Document()
    elem = dom.createElement('element')
    attrs = elem.attributes
    attrs["foo"] = "bar"
    a = attrs.item(0)
    confirm(a.ownerDocument is dom,
            "NamedNodeMap.__setitem__() sets ownerDocument")
    confirm(a.ownerElement is elem,
            "NamedNodeMap.__setitem__() sets ownerElement")
    confirm(a.value == "bar",
            "NamedNodeMap.__setitem__() sets value")
    confirm(a.nodeValue == "bar",
            "NamedNodeMap.__setitem__() sets nodeValue")
    elem.unlink()
    dom.unlink()
コード例 #34
0
    def render(self):
        doc = Document()
        self._render(element=doc, doc=doc)

        #xml = doc.toprettyxml()
        #print xml

        xml = doc.toxml()
        node, dn = createX3DNodeFromString(xml)

        # NOTE: super call here... fix needed?
        super(H3DXMLNode, self).__init__(node, dn)

        self._set_node_refs(self.dn)
        self._rendered = True
        doc.unlink()
コード例 #35
0
def WriteChartDesignerProject(name, filename, maps, map_source="AH OpenStreetMap Mapnik"):

    # sample
    # <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    # <catalog name="Potsdamer_Havel" size="7" version="2">
    #    <Layer name="L16" zoomLvl="16">
    #        <Map name="L16-21544-35120-16-16" mapSource="AH OpenStreetMap Mapnik" ulc="52.34876318, 12.91992188" lrc="52.29504228, 13.00781250" minTileCoordinate="21544/35120" maxTileCoordinate="21559/35135" number="16-21544-35120-16-16"/>
    #    </Layer>
    # </catalog>

    doc = Document()

    root = doc.createElement("catalog")
    root.setAttribute("version", '2')
    root.setAttribute("name", name)
    root.setAttribute("size", "{}".format(len(maps)))

    doc.appendChild(root)

    for _map in maps:

        # Create Element
        tempChild = doc.createElement("Layer")
        tempChild.setAttribute("name", _map.name)
        tempChild.setAttribute("zoomLvl", "{}".format(_map.zoom))

        root.appendChild(tempChild)

        tempMap = doc.createElement("Map")
        tempMap.setAttribute("name", "{} {}".format(_map.name, _map.zoom))
        tempMap.setAttribute("mapSource", map_source)
        tempMap.setAttribute("ulc", "{}, {}".format(_map.NW_lat, _map.NW_lon))
        tempMap.setAttribute("lrc", "{}, {}".format(_map.SE_lat, _map.SE_lon))
        tempMap.setAttribute("minTileCoordinate", "{}/{}".format(_map.ytile_nw, _map.xtile_nw))
        tempMap.setAttribute("maxTileCoordinate", "{}/{}".format(_map.ytile_se, _map.xtile_se))
        tempMap.setAttribute("number", "{}{}{}".format(_map.zoom, _map.ytile_nw, _map.xtile_nw))
        tempChild.appendChild(tempMap)

    doc.writexml(open(filename, 'w'),
                 indent="  ",
                 addindent="  ",
                 newl='\n')

    doc.unlink()
コード例 #36
0
def testAddAttr():
    dom = Document()
    child = dom.appendChild(dom.createElement("abc"))

    child.setAttribute("def", "ghi")
    confirm(child.getAttribute("def") == "ghi")
    confirm(child.attributes["def"].value == "ghi")

    child.setAttribute("jkl", "mno")
    confirm(child.getAttribute("jkl") == "mno")
    confirm(child.attributes["jkl"].value == "mno")

    confirm(len(child.attributes) == 2)

    child.setAttribute("def", "newval")
    confirm(child.getAttribute("def") == "newval")
    confirm(child.attributes["def"].value == "newval")

    confirm(len(child.attributes) == 2)
    dom.unlink()
コード例 #37
0
def testAddAttr():
    dom = Document()
    child = dom.appendChild(dom.createElement("abc"))

    child.setAttribute("def", "ghi")
    confirm(child.getAttribute("def") == "ghi")
    confirm(child.attributes["def"].value == "ghi")

    child.setAttribute("jkl", "mno")
    confirm(child.getAttribute("jkl") == "mno")
    confirm(child.attributes["jkl"].value == "mno")

    confirm(len(child.attributes) == 2)

    child.setAttribute("def", "newval")
    confirm(child.getAttribute("def") == "newval")
    confirm(child.attributes["def"].value == "newval")

    confirm(len(child.attributes) == 2)
    dom.unlink()
コード例 #38
0
ファイル: base.py プロジェクト: rauljuarez/vxvCrawler
def build_xml_results_batch(notify_batch,config):
    
    doc=Document()
    root=doc.createElement('downloads')
    doc.appendChild(root)
    
    for item in notify_batch:
        notif=doc.createElement('download')
        notif.setAttribute('video-id',item['video-id'])
        for result in item['results']:
            video=doc.createElement('video')
     
            video.setAttribute('quality',result['quality'])
            #video.setAttribute('extension',result['extension'])
            video.setAttribute('downloaded',str(result['downloaded']))
            video.setAttribute('uploaded',str(result['uploaded']))
            if result['filename']!=None:
                video.setAttribute('filename',os.path.basename(result['filename']))
            else:
                video.setAttribute('filename','')
                
            url=doc.createElement('url')
            url.appendChild(doc.createTextNode(result['url']))
            video.appendChild(url)
            
            if result['upload_error']!=None:
                up_error=doc.createElement('up-error')
                up_error.appendChild(doc.createTextNode(result['upload_error']))
                video.appendChild(up_error)
            
            if result['download_error']!=None:
                down_error=doc.createElement('down-error')
                down_error.appendChild(doc.createTextNode(result['download_error']))
                video.appendChild(down_error)
            
            notif.appendChild(video)
            
        root.appendChild(notif)
    xml_str=doc.toxml()
    doc.unlink()
    return xml_str    
コード例 #39
0
def WriteMobacProject(name, filename, maps, map_source="OpenSeaMapTEST"):

    # <?xml version="1.0" ?>
    #  <atlas name="OSM-UHW" outputFormat="PNGWorldfile" version="1">
    #    <Layer name="UHW_2_16">
    #      <Map mapSource="OpenSeaMapTEST" maxTileCoordinate="8999168/5517824" minTileCoordinate="8988416/5506048" name="UHW_2_16 16" zoom="16"/>
    #    </Layer>
    #  </atlas>

    doc = Document()

    root = doc.createElement("atlas")
    root.setAttribute("version", '1')
    root.setAttribute("name", name)
    root.setAttribute("outputFormat", "PNGWorldfile")

    doc.appendChild(root)

    for _map in maps:

        # Create Element
        tempChild = doc.createElement("Layer")
        tempChild.setAttribute("name", _map.name)
        root.appendChild(tempChild)

        tempMap = doc.createElement("Map")
        tempMap.setAttribute("maxTileCoordinate", "{}/{}".format(_map.xtile_se * 256, _map.ytile_se * 256))
        tempMap.setAttribute("minTileCoordinate", "{}/{}".format(_map.xtile_nw * 256, _map.ytile_nw * 256))
        tempMap.setAttribute("mapSource", map_source)
        tempMap.setAttribute("zoom", "{}".format(map.zoom))
        tempMap.setAttribute("name", "{} {}".format(_map.name, _map.zoom))

        tempChild.appendChild(tempMap)

    doc.writexml(open(filename, 'w'),
                 indent="  ",
                 addindent="  ",
                 newl='\n')

    doc.unlink()
コード例 #40
0
def writeTrips(trips):
    """
    Writes a list of edges ID (associated by pair (source edge ID / destination edge ID) in an XML file
    """
    i = 0
    doc = Document()
    root = doc.createElement(constants.XML_TRIPS_ELEMENT)
    doc.appendChild(root)

    while i < len(trips):
        trip = doc.createElement(constants.XML_TRIP_ELEMENT)
        trip.setAttribute(constants.XML_TRIP_ID_ATTRIBUTE, str(i))
        trip.setAttribute(constants.XML_TRIP_DEPART_ATTRIBUTE, str(0))
        trip.setAttribute(constants.XML_TRIP_FROM_ATTRIBUTE, trips[i])
        trip.setAttribute(constants.XML_TRIP_TO_ATTRIBUTE, trips[i + 1])
        root.appendChild(trip)
        i += 2

    xmlFile = open(constants.TRIPS_PATH, 'w')
    doc.writexml(xmlFile, '\t', '\t' '\n')
    doc.unlink()
    xmlFile.close()
コード例 #41
0
ファイル: duarouterRoute.py プロジェクト: gitali/ASTra
def writeTrips(trips):    
    """
    Writes a list of edges ID (associated by pair (source edge ID / destination edge ID) in an XML file
    """
    i = 0
    doc = Document()
    root = doc.createElement(constants.XML_TRIPS_ELEMENT)
    doc.appendChild(root)
    
    while i < len(trips):
        trip = doc.createElement(constants.XML_TRIP_ELEMENT)
        trip.setAttribute(constants.XML_TRIP_ID_ATTRIBUTE, str(i))
        trip.setAttribute(constants.XML_TRIP_DEPART_ATTRIBUTE, str(0))
        trip.setAttribute(constants.XML_TRIP_FROM_ATTRIBUTE, trips[i])
        trip.setAttribute(constants.XML_TRIP_TO_ATTRIBUTE, trips[i + 1])
        root.appendChild(trip)
        i += 2
    
    xmlFile = open(constants.TRIPS_PATH, 'w')
    doc.writexml(xmlFile, '\t', '\t' '\n')
    doc.unlink()
    xmlFile.close()
コード例 #42
0
def ExportLog( filename, sessions ):
    doc = Document()
    docSessions = doc.createElement( "NetworkSessions" )
    for session in sessions:
        docSession = doc.createElement("Session")
        docSession.setAttribute( "User", session.mUser )
        docSession.setAttribute( "Host", session.mHost )
        
        docFiles = doc.createElement("Files")
        for file in session.mFiles:
            docFile = doc.createElement("File")
            docFile.setAttribute( "Date", str(file.mDate) )
            docFileName = doc.createTextNode( file.mName )
            docFile.appendChild( docFileName )
            docSession.appendChild( docFile )
            
        docSessions.appendChild( docSession )

    doc.appendChild( docSessions )
        
    file = open( filename, 'w' )
    file.write( doc.toprettyxml() )
    doc.unlink()
    file.close()
コード例 #43
0
    def write_refs_to_xml(path, services):
        header = '<?xml version="1.0" encoding="utf-8"?>\n<!--  {} -->\n<!-- {} -->\n<channels>\n'.format(
            "Created in DemonEditor.", datetime.now().strftime("%d.%m.%Y %H:%M:%S"))
        doc = Document()
        lines = [header]

        for srv in services:
            srv_type = srv.type
            if srv_type is BqServiceType.IPTV:
                channel_child = doc.createElement("channel")
                channel_child.setAttribute("id", str(srv.num))
                data = srv.data.strip().split(":")
                channel_child.appendChild(doc.createTextNode(":".join(data[:10])))
                comment = doc.createComment(srv.name)
                lines.append("{} {}\n".format(str(channel_child.toxml()), str(comment.toxml())))
            elif srv_type is BqServiceType.MARKER:
                comment = doc.createComment(srv.name)
                lines.append("{}\n".format(str(comment.toxml())))

        lines.append("</channels>")
        doc.unlink()

        with open(path, "w", encoding="utf-8") as f:
            f.writelines(lines)
コード例 #44
0
def csomag_XML_elem(cs_felm, cs_azon, cs_nev, cs_pontsz, cs_gen, cs_hat,
                    cs_tom, cs_MD5, genfolder):
    """ XML minidom-document létrehozása a csomag adataival és a csomag_log rekord kezelése"""
    doc = Document()

    # csomag elem létrehozása
    csomag = doc.createElement('csomag')
    csomag.setAttribute("azonosito", '%s' % str(cs_azon))
    csomag.setAttribute("nev", '%s' % cs_nev)
    csomag.setAttribute("pontszam", '%s' % str(cs_pontsz))
    doc.appendChild(csomag)

    # a csomag gyermek elemeinek létrehozása
    generalas = doc.createElement('generalas')
    generalas_tartalom = doc.createTextNode('%s' % cs_gen)
    generalas.appendChild(generalas_tartalom)
    csomag.appendChild(generalas)

    hatarido = doc.createElement('hatarido')
    hatarido_tartalom = doc.createTextNode('%s' % cs_hat)
    hatarido.appendChild(hatarido_tartalom)
    csomag.appendChild(hatarido)

    muvelet = doc.createElement('muvelet')
    csomag.appendChild(muvelet)

    hash = doc.createElement('hash')
    csomag.appendChild(hash)

    # a művelet gyermek elemeinek létrehozása
    tomorites = doc.createElement('tomorites')
    tomorites_tartalom = doc.createTextNode('%s' % cs_tom)
    tomorites.appendChild(tomorites_tartalom)
    muvelet.appendChild(tomorites)

    # a művelet gyermek elemeinek létrehozása
    md5szerver = doc.createElement('MD5_szerver')
    md5szerver_tartalom = doc.createTextNode('%s' % cs_MD5)
    md5szerver.appendChild(md5szerver_tartalom)
    hash.appendChild(md5szerver)

    fname = genfolder + '/' + cs_felm + '/' + cs_nev + '.xml'
    # XML kiírása
    doc.writexml(open(fname, 'w'), indent="  ", addindent="  ", newl='\n')
    doc.unlink()

    if os.path.isfile(fname):
        queryLogId = QtSql.QSqlQuery()
        siker = queryLogId.exec_(
            '''SELECT package_id FROM csomag_log WHERE csomag_azon = %s;''' %
            (cs_azon))
        if siker:
            if queryLogId.size() == 1:
                queryLogId.next()
                return queryLogId.value(0), 2
            elif queryLogId.size() > 1:
                QtWidgets.QMessageBox.warning(
                    None, u"Csomag-log",
                    u"Csomag-log rekord lekérdezési hiba.")
                return 0, 0
        else:
            if queryLogId.lastError().type() != 0:
                QtWidgets.QMessageBox.warning(
                    None, u"Hiba:",
                    u"Hiba típus: %s" % str(queryLogId.lastError().text()))
                return 0, 0

        queryLog = QtSql.QSqlQuery()
        siker = queryLog.exec_(
            '''INSERT INTO csomag_log(felmero,csomag_azon,csomag_nev,cs_pontszam,cs_generalas,cs_hatarido,m_tomorites,hash_md5_szerver) 
            VALUES('%s',%s,'%s',%s,'%s','%s','%s','%s') RETURNING package_id ;'''
            % (cs_felm, cs_azon, cs_nev, cs_pontsz, cs_gen, cs_hat, cs_tom,
               cs_MD5))
        if siker:
            if queryLog.size() == 1:
                queryLog.next()
                return queryLog.value(0), 1
            else:
                QtWidgets.QMessageBox.warning(
                    None, u"Csomag-log", u"Csomag-log rekord rögzítési hiba.")
                return 0, 0

        else:
            if queryLog.lastError().type() != 0:
                QtWidgets.QMessageBox.warning(
                    None, u"Hiba:",
                    u"Hiba típus: %s" % str(queryLog.lastError().text()))
                return 0, 0

    else:
        print("No XML - No PackMan!")
        return 0, 0
コード例 #45
0
                        if id == args.identity:
                            # Add element which id is equal with args.identity (only once)
                            root.appendChild(elem)
                            firstFound = True
                    else:
                        if args.identity is None and parentId == 0:
                            root.appendChild(elem)  # direct child of root element

                        # Finding parent of actual element by parentId
                        elementList = doc.getElementsByTagName('Process')
                        for parent in elementList:
                            if parent.getAttribute('ID') == str(parentId):
                                parent.appendChild(elem)
                                break

                # Close connection with CIMOM
                conn.disconnect()

                # Write document, and after unlink it and close output XML file
                doc.writexml(output, addindent="    ", newl='\n')
                doc.unlink()
                output.close()

            except lmiwbem.lmiwbem_core.ConnectionError as connErr:
                print("(ERROR) You cannot connect to " + host)
                print("\t" + str(connErr))
                continue

# Closing source CSV file
source.close()
コード例 #46
0
ファイル: ad_to_swn.py プロジェクト: seanmhanson/ad-to-swn
def write_xml(contact_list, file_name, accountID):

	doc = Document()
	
	# Write Header
	batch = doc.createElement("contactBatch")
	batch.setAttribute("xmlns", "http://www.sendwordnow.com")
	batch.setAttribute("version", "1.0.2")

	batch_pd = doc.createElement("batchProcessingDirectives")

	batch_acc = doc.createElement("accountID")
	batch_acc.setAttribute("username", accountID)

	batch_file = doc.createElement("batchFile")
	batch_file.setAttribute("requestFileName", file_name)

	batch_dcnib = doc.createElement("batchProcessingOption")
	batch_dcnib.setAttribute("name", "DeleteContactsNotInBatch")
	batch_dcnib.setAttribute("value", "true")

	batch_pd.appendChild(batch_acc)
	batch_pd.appendChild(batch_file)
	batch_pd.appendChild(batch_dcnib)

	batch.appendChild(batch_pd)

	# Write Contacts in Contact List
	batch_cl = doc.createElement("batchContactList")

	for entry in contact_list:
		contact = doc.createElement("contact")
		contact.setAttribute("contactID", entry.contactID)
		contact.setAttribute("action", "AddOrModify")

		for duple in entry.contactFields:
			contactField = doc.createElement("contactField")
			contactField.setAttribute("name", duple[0])
			contactField.appendChild(doc.createTextNode(duple[1]))
			contact.appendChild(contactField)
		for duple in entry.customContactFields:
			contactField = doc.createElement("contactField")
			contactField.setAttribute("name", "CustomField")
			contactField.setAttribute("customName", duple[0])
			contactField.appendChild(doc.createTextNode(duple[1]))
			contact.appendChild(contactField)
		groupList = doc.createElement("groupList")
		for group in entry.groupList:
			groupName = doc.createElement("groupName")
			groupName.appendChild(doc.createTextNode(group))
			groupList.appendChild(groupName)
		contact.appendChild(groupList)

		contactPointList = doc.createElement("contactPointList")
		for cP in entry.contactPoints:
			if len(cP) == 4:
				contactPoint = doc.createElement("contactPoint")
				contactPoint.setAttribute("type", cP[0])

				contactPointField = doc.createElement("contactPointField")
				contactPointField.setAttribute("name", "Label")
				contactPointField.appendChild(doc.createTextNode(cP[1]))
				contactPoint.appendChild(contactPointField)

				contactPointField = doc.createElement("contactPointField")
				contactPointField.setAttribute("name", "CountryCode")
				contactPointField.appendChild(doc.createTextNode(cP[2]))
				contactPoint.appendChild(contactPointField)

				contactPointField = doc.createElement("contactPointField")
				contactPointField.setAttribute("name", "Number")
				contactPointField.appendChild(doc.createTextNode(cP[3]))
				contactPoint.appendChild(contactPointField)
				contactPointList.appendChild(contactPoint)
			if len(cP) == 3:
				contactPoint = doc.createElement("contactPoint")
				contactPoint.setAttribute("type", cP[0])

				contactPointField = doc.createElement("contactPointField")
				contactPointField.setAttribute("name", "Label")
				contactPointField.appendChild(doc.createTextNode(cP[1]))
				contactPoint.appendChild(contactPointField)

				contactPointField = doc.createElement("contactPointField")
				contactPointField.setAttribute("name", "Address")
				contactPointField.appendChild(doc.createTextNode(cP[2]))
				contactPoint.appendChild(contactPointField)
				contactPointList.appendChild(contactPoint)
		contact.appendChild(contactPointList)
		batch_cl.appendChild(contact)
	batch.appendChild(batch_cl)
	doc.appendChild(batch)
	
	doc.writexml(open("writing_"+file_name, 'w', encoding='utf-8'),
				 indent="	",
				 addindent="	",
				 newl="\n",
				 encoding="UTF-8")
	doc.unlink()
コード例 #47
0
    # Write Text
    nodeText = doc.createTextNode(value[1])
    tempChild.appendChild(nodeText)

    # Create Element
    subjectRegisted = doc.createElement('subject-registed')
    studentinfo.appendChild(subjectRegisted)

    # Create Element
    tempChild = doc.createElement('subject-name')
    subjectRegisted.appendChild(tempChild)

    # Write Text
    nodeText = doc.createTextNode(value[2])
    tempChild.appendChild(nodeText)

    # Create Element
    tempChild = doc.createElement('subject-ID')
    subjectRegisted.appendChild(tempChild)

    # Write Text
    nodeText = doc.createTextNode(value[3])
    tempChild.appendChild(nodeText)

doc.writexml(open('output.xml', 'w'), indent="  ", addindent=" ", newl='\n')

doc.unlink()

print 'Write file complete!'
コード例 #48
0
def testElement():
    dom = Document()
    dom.appendChild(dom.createElement("abc"))
    confirm(dom.documentElement)
    dom.unlink()
コード例 #49
0
def testElement():
    dom = Document()
    dom.appendChild(dom.createElement("abc"))
    confirm(dom.documentElement)
    dom.unlink()
コード例 #50
0
ファイル: transformer.py プロジェクト: Acquil/greevil-app
class XmlTransformer(object):
    """
    Builds an XML from a python dictionary
    """
    doc = None

    def __init__(self, data: dict):

        self.doc = Document()

        if len(data) == 1:
            # only one root element
            root_name = str(list(data)[0])
        else:
            # set "response" as default root element
            root_name = "response"
            data_temp = data
            data = {root_name: data_temp}

        self.root = self.doc.createElement(root_name)
        self.doc.appendChild(self.root)
        # Build XML
        self.build(self.root, data[root_name])

    def build(self, parent, structure):
        """
        Recursively build XML
        :param parent: same as structure, initially root tag
        :param structure: dictionary, list or number/string
        :return: None
        """
        if type(structure) == dict:
            for item in structure:
                tag = self.doc.createElement(item)
                parent.appendChild(tag)
                self.build(tag, structure[item])

        elif type(structure) == list:

            grand_parent = parent.parentNode
            tag_name = parent.tagName
            grand_parent.removeChild(parent)

            for list_item in structure:
                tag = self.doc.createElement(tag_name)
                self.build(tag, list_item)
                grand_parent.appendChild(tag)

        # Take int/float/double/string as string
        else:
            data = str(structure)
            tag = self.doc.createTextNode(data)
            parent.appendChild(tag)

    def unlink(self):
        """
        Unlink all children
        :return: None
        """
        self.doc.unlink()
        return None

    def __repr__(self):
        """
        For repr()
        :return: string
        """
        return self.doc.toprettyxml("")

    def __str__(self):
        """
        For print()
        :return: string
        """
        return self.doc.toprettyxml(indent="\t")
コード例 #51
0
def writeDocument(sourceDataset, targetDataset, xmlFileName):

    desc = arcpy.Describe(sourceDataset)
    descT = arcpy.Describe(targetDataset)
    sourcePath = getLayerPath(desc)
    targetPath = getLayerPath(descT)

    ## Added May2016. warn user if capabilities are not correct, exit if not a valid layer
    if not dla.checkServiceCapabilities(sourcePath, False):
        dla.addMessage(
            sourceDataset +
            ' Does not appear to be a feature service layer, exiting. Check that you selected a layer not a service'
        )
        return False
    if not dla.checkServiceCapabilities(targetPath, False):
        dla.addMessage(
            targetDataset +
            ' Does not appear to be a feature service layer, exiting. Check that you selected a layer not a service'
        )
        return False

    xmlDoc = Document()
    root = xmlDoc.createElement('SourceTargetMatrix')
    xmlDoc.appendChild(root)
    root.setAttribute("version", '1.1')
    root.setAttribute("xmlns:esri", 'http://www.esri.com')

    dataset = xmlDoc.createElement("Datasets")
    root.appendChild(dataset)
    setSourceTarget(dataset, xmlDoc, "Source", sourcePath)
    setSourceTarget(dataset, xmlDoc, "Target", targetPath)

    setSpatialReference(dataset, xmlDoc, desc, "Source")
    setSpatialReference(dataset, xmlDoc, descT, "Target")

    setSourceTarget(dataset, xmlDoc, "ReplaceBy", "")

    fieldroot = xmlDoc.createElement("Fields")
    root.appendChild(fieldroot)

    fields = getFields(descT, targetDataset)
    sourceFields = getFields(desc, sourceDataset)
    sourceNames = [
        field.name[field.name.rfind(".") + 1:] for field in sourceFields
    ]
    upperNames = [nm.upper() for nm in sourceNames]

    #try:
    for field in fields:

        fNode = xmlDoc.createElement("Field")
        fieldroot.appendChild(fNode)
        fieldName = field.name[field.name.rfind(".") + 1:]
        matchSourceFields(xmlDoc, fNode, field, fieldName, sourceNames,
                          upperNames)

    # write the source field values
    setSourceFields(root, xmlDoc, sourceFields)
    setTargetFields(root, xmlDoc, fields)
    # Should add a template section for value maps, maybe write domains...
    # could try to preset field mapping and domain mapping...

    # add some data to the document
    writeDataSample(xmlDoc, root, sourceNames, sourceDataset, 10)
    # write it out
    xmlDoc.writexml(open(xmlFileName, 'w'),
                    indent="  ",
                    addindent="  ",
                    newl='\n')
    xmlDoc.unlink()
コード例 #52
0
    def cod():
        from xml.dom.minidom import Document
        conn = sqlite3.connect('autonomos.db')
        cursor = conn.cursor()
        id = int(wd_id.get())
        #id_1 = id -1
        lista = []
        cursor.execute("""
            SELECT * FROM autonomos;
            """)
        for linha in cursor.fetchall():
            lista.append(linha[0:9])
        # document create
        doc = Document()
        # element
        root = doc.createElement('esocial')
        evtRemun = doc.createElement('evtRemun')
        ideEvento = doc.createElement('ideEvento')
        indRetif = doc.createElement('indRetif')
        indApuracao = doc.createElement('indApuracao')
        perApur = doc.createElement('perApur')
        tpAmb = doc.createElement('tpAmb')
        procEmi = doc.createElement('procEmi')
        verProc = doc.createElement('verProc')
        ideEmpregador = doc.createElement('ideEmpregador')
        tpInsc = doc.createElement('tpInsc')
        nrInsc = doc.createElement('nrInsc')
        ideTrabalhador = doc.createElement('ideTrabalhador')
        cpfTrab = doc.createElement('cpfTrab')
        nisTrab = doc.createElement('nisTrab')
        infoComplem = doc.createElement('infoComplem')
        nmTrab = doc.createElement('nmTrab')
        dtNascto = doc.createElement('dtNascto')
        dmDev = doc.createElement('dmDev')
        ideDmDev = doc.createElement('ideDmDev')
        codCateg = doc.createElement('codCateg')
        infoPerApur = doc.createElement('infoPerApur')
        ideEstabLot = doc.createElement('ideEstabLot')
        tpInsc2 = doc.createElement('tpInsc')
        nrInsc2 = doc.createElement('nrInsc')
        codLotacao = doc.createElement('codLotacao')
        remunPerApur = doc.createElement('remunPerApur')
        itensRemun = doc.createElement('itensRemun')
        codRubr = doc.createElement('codRubr')
        ideTrabRubr = doc.createElement('ideTrabRubr')
        vrRubr = doc.createElement('vrRubr')
        infoComplCont = doc.createElement('infoComplCont')
        codCBO = doc.createElement('codCBO')

        # child
        doc.appendChild(root)
        root.appendChild(evtRemun)
        evtRemun.appendChild(ideEvento)
        ideEvento.appendChild(indRetif)
        ideEvento.appendChild(indApuracao)
        ideEvento.appendChild(perApur)
        ideEvento.appendChild(tpAmb)
        ideEvento.appendChild(procEmi)
        ideEvento.appendChild(verProc)
        evtRemun.appendChild(ideEmpregador)
        ideEmpregador.appendChild(tpInsc)
        ideEmpregador.appendChild(nrInsc)
        evtRemun.appendChild(ideTrabalhador)
        ideTrabalhador.appendChild(cpfTrab)
        ideTrabalhador.appendChild(nisTrab)
        ideTrabalhador.appendChild(infoComplem)
        infoComplem.appendChild(nmTrab)
        infoComplem.appendChild(dtNascto)
        evtRemun.appendChild(dmDev)
        dmDev.appendChild(ideDmDev)
        dmDev.appendChild(codCateg)
        dmDev.appendChild(infoPerApur)
        infoPerApur.appendChild(ideEstabLot)
        ideEstabLot.appendChild(tpInsc2)
        ideEstabLot.appendChild(nrInsc2)
        ideEstabLot.appendChild(codLotacao)
        ideEstabLot.appendChild(remunPerApur)
        remunPerApur.appendChild(itensRemun)
        itensRemun.appendChild(codRubr)
        itensRemun.appendChild(ideTrabRubr)
        itensRemun.appendChild(vrRubr)
        itensRemun.appendChild(codRubr)
        itensRemun.appendChild(ideTrabRubr)
        itensRemun.appendChild(vrRubr)
        dmDev.appendChild(infoComplCont)
        infoComplCont.appendChild(codCBO)
        # receive data
        ident = str(lista[id - 1][1])
        a = str(1)  #indretif
        b = str(1)  #indapuracao
        data_atual = date.today()
        c = data_atual.strftime('%Y-%m')
        d = str(1)  #tpamb
        e = str(1)  #procEmi
        f = str("1.0")  #verProc
        g = str(1)  #tpinsc
        h = str("03582844")  #nrinsc
        i = str(lista[id - 1][3])  #cpf
        j = str(lista[id - 1][4])  #nis
        k = str(lista[id - 1][1])  #nome
        nascimento = str(lista[id - 1][2])
        data = datetime.strptime(nascimento, "%Y%m%d").date()
        l = str(data)  #DTNASCTO
        m = str(1)  #idedmdev
        n = str(lista[id - 1][6])  #codcateg
        o = str("1")  #tpinsc
        p = str("03582844000186")  #nrisnc
        q = str("C01S000003")  #codLotacao
        r = str(lista[id - 1][5])  #codcbo
        carreta = lista[id - 1][8]
        remuneracao = lista[id - 1][7]
        remun = float(remuneracao)
        if carreta == '1':
            frete = remun * 0.20
            inss = frete * 0.11
        else:
            frete = remun * 0.20

        # atributes
        root.setAttribute(
            'xmlns', 'http://www.esocial.gov.br/schema/evt/evtRemun/v02_04_02')
        evtRemun.setAttribute('Id', ident)
        # text mode in child
        txt1 = doc.createTextNode(a)
        indRetif.appendChild(txt1)
        txt2 = doc.createTextNode(b)
        indApuracao.appendChild(txt2)
        txt3 = doc.createTextNode(c)
        perApur.appendChild(txt3)
        txt4 = doc.createTextNode(d)
        tpAmb.appendChild(txt4)
        txt5 = doc.createTextNode(e)
        procEmi.appendChild(txt5)
        txt6 = doc.createTextNode(f)
        verProc.appendChild(txt6)
        txt7 = doc.createTextNode(g)
        tpInsc.appendChild(txt7)
        txt8 = doc.createTextNode(h)
        nrInsc.appendChild(txt8)
        txt9 = doc.createTextNode(i)
        cpfTrab.appendChild(txt9)
        txt10 = doc.createTextNode(j)
        nisTrab.appendChild(txt10)
        txt11 = doc.createTextNode(k)
        nmTrab.appendChild(txt11)
        txt12 = doc.createTextNode(l)
        dtNascto.appendChild(txt12)
        txt13 = doc.createTextNode(m)
        ideDmDev.appendChild(txt13)
        txt14 = doc.createTextNode(n)
        codCateg.appendChild(txt14)
        txt16 = doc.createTextNode(o)
        tpInsc2.appendChild(txt16)
        txt17 = doc.createTextNode(p)
        nrInsc2.appendChild(txt17)
        txt18 = doc.createTextNode(q)
        codLotacao.appendChild(txt18)
        txt25 = doc.createTextNode(r)
        codCBO.appendChild(txt25)
        nomedoxml = ident + ".xml"
        doc.writexml(open(nomedoxml, 'w'), addindent='    ', newl='\n')
        doc.unlink()
        print("Exportado com Sucesso")
コード例 #53
0
ファイル: test_minidom.py プロジェクト: mcyril/ravel-ftn
# test for xml.dom.minidom
コード例 #54
0
def downloadAndWriteWeather(woeid):
	seconds=int(datetime.now().strftime("%s"))
	currenttime=datetime.now().strftime("%I:%M %p")
	
	currentdate=datetime.now().strftime("%A %m/%d/%Y")

	weather=getWeather(woeid)

	current_condition=weather['current_condition']
	current_temp=weather['current_temp']
	current_code=weather['current_code']
	humidity=weather['humidity']
	pressure=weather['pressure']
	rising=weather['rising']
	winddirection=weather['winddirection']
	windspeed=weather['windspeed']
	windchill=weather['windchill']
	sunrise=weather['sunrise']
	sunset=weather['sunset']

	getIndoorTempCmd="/var/www/html/BERTHA/therm.py -q | grep CurrentTemp | sed 's/CurrentTemp //'";
	# IndoorTemp=subprocess.check_output('{}'.format(getIndoorTempCmd),shell=True)
	#IndoorTemp=subprocess.Popen(format(getIndoorTempCmd),shell=True)
	IndoorTemp="NA"

	getIndoorSettingCmd="/var/www/html/BERTHA/therm.py -q | grep CoolSetpoint | sed 's/CoolSetpoint //'"
	# IndoorSetting=subprocess.check_output('{}'.format(getIndoorSettingCmd),shell=True)
	#IndoorSetting=subprocess.Popen(format(getIndoorSettingCmd),shell=True)
	IndoorSetting="NA"


	day0date=weather['forecasts'][0]['date']
	day0day=weather['forecasts'][0]['day']
	day0high=weather['forecasts'][0]['high']
	day0low=weather['forecasts'][0]['low']
	day0code=weather['forecasts'][0]['code']
	day0condition=weather['forecasts'][0]['condition']
	day1date=weather['forecasts'][1]['date']
	day1day=weather['forecasts'][1]['day']
	day1high=weather['forecasts'][1]['high']
	day1low=weather['forecasts'][1]['low']
	day1code=weather['forecasts'][1]['code']
	day1condition=weather['forecasts'][1]['condition']
	day2date=weather['forecasts'][2]['date']
	day2day=weather['forecasts'][2]['day']
	day2high=weather['forecasts'][2]['high']
	day2low=weather['forecasts'][2]['low']
	day2code=weather['forecasts'][2]['code']
	day2condition=weather['forecasts'][2]['condition']
	day3date=weather['forecasts'][3]['date']
	day3day=weather['forecasts'][3]['day']
	day3high=weather['forecasts'][3]['high']
	day3low=weather['forecasts'][3]['low']
	day3code=weather['forecasts'][3]['code']
	day3condition=weather['forecasts'][3]['condition']
	day4date=weather['forecasts'][4]['date']
	day4day=weather['forecasts'][4]['day']
	day4high=weather['forecasts'][4]['high']
	day4low=weather['forecasts'][4]['low']
	day4code=weather['forecasts'][4]['code']
	day4condition=weather['forecasts'][4]['condition']

	doc=Document()
	data=doc.createElement('data')
	doc.appendChild(data)

	now=doc.createElement('now')
	now.setAttribute("date",currentdate)
	now.setAttribute("time",currenttime)
	data.appendChild(now)

	astral=doc.createElement('astral')
	astral.setAttribute("sunrise",sunrise)
	astral.setAttribute("sunset",sunset)

	pos=position()
	moonphasename=phase(pos)
	moonphasenum=phasenum(pos)

	astral.setAttribute("moonphase",moonphasename)
	astral.setAttribute("moonphasenum",moonphasenum)
	data.appendChild(astral)

	weather=doc.createElement('weather')
	data.appendChild(weather)
	current=doc.createElement('current')
	weather.appendChild(current)
	current.setAttribute("temp",current_temp)
	current.setAttribute("humidity",humidity)
	current.setAttribute("pressure",pressure)
	current.setAttribute("rising",rising)
	current.setAttribute("winddirection",winddirection)
	current.setAttribute("windspeed",windspeed)
	current.setAttribute("windchill",windchill)
	current.setAttribute("condition",current_condition)
	current.setAttribute("code",current_code)
	current.setAttribute("indoor",IndoorTemp)
	current.setAttribute("setting",IndoorSetting)
	today=doc.createElement('today')
	today.setAttribute("high",day0high)
	today.setAttribute("low",day0low)
	forecast=doc.createElement('forecast')
	weather.appendChild(forecast)
	day0=doc.createElement('day0')
	day0.setAttribute("date",day0date)
	day0.setAttribute("day",day0day)
	day0.setAttribute("high",day0high)
	day0.setAttribute("low",day0low)
	day0.setAttribute("code",day0code)
	day0.setAttribute("precip",'100')
	day0.setAttribute("condition",day0condition)
	day1=doc.createElement('day1')
	day1.setAttribute("date",day1date)
	day1.setAttribute("day",day1day)
	day1.setAttribute("high",day1high)
	day1.setAttribute("low",day1low)
	day1.setAttribute("code",day1code)
	day1.setAttribute("precip",'100')
	day1.setAttribute("condition",day1condition)
	day2=doc.createElement('day2')
	day2.setAttribute("date",day2date)
	day2.setAttribute("day",day2day)
	day2.setAttribute("high",day2high)
	day2.setAttribute("low",day2low)
	day2.setAttribute("code",day2code)
	day2.setAttribute("precip",'100')
	day2.setAttribute("condition",day2condition)
	day3=doc.createElement('day3')
	day3.setAttribute("date",day3date)
	day3.setAttribute("day",day3day)
	day3.setAttribute("high",day3high)
	day3.setAttribute("low",day3low)
	day3.setAttribute("code",day3code)
	day3.setAttribute("precip",'100')
	day3.setAttribute("condition",day3condition)
	day4=doc.createElement('day4')
	day4.setAttribute("date",day4date)
	day4.setAttribute("day",day4day)
	day4.setAttribute("high",day4high)
	day4.setAttribute("low",day4low)
	day4.setAttribute("code",day4code)
	day4.setAttribute("precip",'100')
	day4.setAttribute("condition",day4condition)
	forecast.appendChild(day0)
	forecast.appendChild(day1)
	forecast.appendChild(day2)
	forecast.appendChild(day3)
	forecast.appendChild(day4)
	data.appendChild(weather)

	# doc.writexml(open("/usr/local/HyperClock/AstralData.txt","wb"),indent="  ",addindent="  ",newl='\n')
	doc.writexml(open(HyperConfig.cfg_AstralDataFile,"wb"),indent="  ",addindent="  ",newl='\n')

	doc.unlink()