Create an XML file.

    Takes a path to where the XML file should be created
    and a metadata dictionary.
339827
def pydict2xml(filename, metadata_dict, **kwargs):
    
    try:
        f = open(filename, 'w')
        f.write(pydict2xmlstring(metadata_dict, **kwargs).encode('utf-8'))
        f.close()
    except:
        raise MetadataGeneratorException(
            'Failed to create an XML file. Filename: %s' % (filename)
        )
1050286
protected function buildXml()
    {
        $_config =& CKFinder_Connector_Core_Factory::getInstance("Core_Config");
        if (!$this->_currentFolder->checkAcl(CKFINDER_CONNECTOR_ACL_FILE_VIEW)) {
            $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_UNAUTHORIZED);
        }

        // Map the virtual path to the local server path.
        $_sServerDir = $this->_currentFolder->getServerPath();

        // Create the "Files" node.
        $oFilesNode = new Ckfinder_Connector_Utils_XmlNode("Files");
        $this->_connectorNode->addChild($oFilesNode);

        if (!is_dir($_sServerDir)) {
            $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_FOLDER_NOT_FOUND);
        }

        $files = array();
        $thumbFiles = array();

        if ($dh = @opendir($_sServerDir)) {
            while (($file = readdir($dh)) !== false) {
                if ($file != "." && $file != ".." && !is_dir($_sServerDir . $file)) {
                    $files[] = $file;
                }
            }
            closedir($dh);
        } else {
            $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_ACCESS_DENIED);
        }

        $resourceTypeInfo = $this->_currentFolder->getResourceTypeConfig();

        if (sizeof($files)>0) {
            $_thumbnailsConfig = $_config->getThumbnailsConfig();
            $_thumbServerPath = '';
            $_showThumbs = (!empty($_GET['showThumbs']) && $_GET['showThumbs'] == 1);
            if ($_thumbnailsConfig->getIsEnabled() && ($_thumbnailsConfig->getDirectAccess() || $_showThumbs)) {
                $_thumbServerPath = $this->_currentFolder->getThumbsServerPath();
            }

            natcasesort($files);
            $i=0;
            foreach ($files as $file) {
                $filemtime = @filemtime($_sServerDir . $file);

                //otherwise file doesn't exist or we can't get it's filename properly
                if ($filemtime !== false) {
                    $filename = CKFinder_Connector_Utils_Misc::mbBasename($file);
                    if (!$resourceTypeInfo->checkExtension($filename, false)) {
                        continue;
                    }
                    if ($resourceTypeInfo->checkIsHiddenFile($filename)) {
                        continue;
                    }
                    $oFileNode[$i] = new Ckfinder_Connector_Utils_XmlNode("File");
                    $oFilesNode->addChild($oFileNode[$i]);
                    $oFileNode[$i]->addAttribute("name", CKFinder_Connector_Utils_FileSystem::convertToConnectorEncoding(CKFinder_Connector_Utils_Misc::mbBasename($file)));
                    $oFileNode[$i]->addAttribute("date", @date("YmdHi", $filemtime));
                    if (!empty($_thumbServerPath) && preg_match(CKFINDER_REGEX_IMAGES_EXT, $filename)) {
                        if (file_exists($_thumbServerPath . $filename)) {
                            $oFileNode[$i]->addAttribute("thumb", $filename);
                        }
                        elseif ($_showThumbs) {
                            $oFileNode[$i]->addAttribute("thumb", "?" . $filename);
                        }
                    }
                    $size = filesize($_sServerDir . $file);
                    if ($size && $size<1024) {
                        $size = 1;
                    }
                    else {
                        $size = (int)round($size / 1024);
                    }
                    $oFileNode[$i]->addAttribute("size", $size);
                    $i++;
                }
            }
        }
    }
1345160
def NewFile(self, filename, encoding, options):
        
        ret = libxml2mod.xmlReaderNewFile(self._o, filename, encoding, options)
        return ret
605268
def load_xml(self, filepath):
        
        # Parse the XML file
        vot = vo.parse_single_table(filepath)
        self.raw = np.array([list(i) for i in vot.array]).T

        # Parse the filter metadata
        for p in [str(p).split() for p in vot.params]:

            # Extract the key/value pairs
            key = p[1].split('"')[1]
            val = p[-1].split('"')[1]

            # Do some formatting
            flt1 = p[2].split('"')[1] == 'float'
            flt2 = p[3].split('"')[1] == 'float'
            if flt1 or flt2:
                val = float(val)

            else:
                val = val.replace('b&apos;', '')\
                         .replace('&apos', '')\
                         .replace('&amp;', '&')\
                         .strip(';')

            # Set the attribute
            if key != 'Description':
                setattr(self, key, val)

        # Create some attributes
        self.path = filepath
        self.pixels_per_bin = self.raw.shape[-1]
        self.n_bins = 1
14127
def create(self, path, data=None):
        
        node = self.current[-1]
        path = self._splitpath(path)
        n_items = len(path)
        for n, item in enumerate(path):
            tag, attribs = self._splittag(item)

            # The leaf node is always newly created.
            if n == n_items-1:
                node = node.add(Node(tag, attribs))
                break

            # Parent nodes are only created if they do not exist yet.
            existing = node.get_child(tag, attribs)
            if existing is not None:
                node = existing
            else:
                node = node.add(Node(tag, attribs))
        if data:
            node.text = unquote(data)
        return node
844405
def createFileParserCtxt(filename):
    
    ret = libxml2mod.xmlCreateFileParserCtxt(filename)
    if ret is None:raise parserError('xmlCreateFileParserCtxt() failed')
    return parserCtxt(_obj=ret)
592417
def from_file(cls, xml_path):
    """"""
    try:
      parsed_xml = cls._parse(xml_path)
    except OSError as e:
      raise XmlParser.XmlError("Problem reading xml file at {}: {}".format(xml_path, e))
    return cls(xml_path, parsed_xml)
84963
def create(cls, fpath):
        ""
        fpath = _expand_path(fpath)
        assert(fpath.suffix == '.yml')
        if fpath.exists(): return
        fpath.parent.mkdir(parents=True, exist_ok=True)
        with open(fpath, 'w') as yaml_file:
            yaml.dump(cls.DEFAULT_CONFIG, yaml_file, default_flow_style=False)
414008
def from_file(cls, file_path, validate=True):
        
        return xmlmap.load_xmlobject_from_file(file_path, xmlclass=cls, validate=validate)
1373409
def save_metadata(self, file_path):
    
    data = self.metadata
    with open(file_path, 'w')  as out_file:
      json.dump(data, out_file)
517409
def File(self, name, directory=None, create=1):
        
        return self._create_node(name, self.env.fs.File, directory, create)
355765
def _parse_xml(self, xml):
        
        vms("Parsing <static> XML child tag.", 2)
        for child in xml:
            if "path" in child.attrib and "target" in child.attrib:
                if child.tag == "file":
                    self.files.append({"source": child.attrib["path"],
                                       "target": child.attrib["target"]})
                elif child.tag == "folder":
                    self.folders.append({"source": child.attrib["path"],
                                         "target": child.attrib["target"]})
464233
def to_xml(xml_builder)
      attributes = {
          'metadata:type' => type,
      }

      if value.nil?
        attributes['metadata:null'] = 'true'
        xml_builder['data'].send(name.to_sym, attributes)
      else
        xml_builder['data'].send(name.to_sym, attributes, xml_value)
      end
    end
1158456
def create_metadata(info = {})
            skeleton = <<-XMP
            <?packet begin="\xef\xbb\xbf" id="W5M0MpCehiHzreSzNTczkc9d"?>
              <x:xmpmeta xmlns:x="adobe:ns:meta/">
                <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
                  <rdf:Description rdf:about="" xmlns:pdf="http://ns.adobe.com/pdf/1.3/">
                  </rdf:Description>
                </rdf:RDF>
              </x:xmpmeta>
            <?xpacket end="w"?>
            XMP

            xml =
                if self.Catalog.Metadata.is_a?(Stream)
                    self.Catalog.Metadata.data
                else
                    skeleton
                end

            doc = REXML::Document.new(xml)
            desc = doc.elements['*/*/rdf:Description']

            info.each do |name, value|
                elt = REXML::Element.new "pdf:#{name}"
                elt.text = value

                desc.elements << elt
            end

            xml = ""; doc.write(xml, 4)

            if self.Catalog.Metadata.is_a?(Stream)
                self.Catalog.Metadata.data = xml
            else
               self.Catalog.Metadata = Stream.new(xml)
            end

            self.Catalog.Metadata
        end
924066
def writexml(self, filename_or_file=None, indent="  ", newl=os.linesep, 
                 encoding="UTF-8"):
        
        if not filename_or_file:
            filename_or_file = self.filename
        if isinstance(filename_or_file, (str, unicode)):
            filename_or_file = open(filename_or_file, "wb")
        xmlstr = self.toxml(indent, newl, encoding)
        filename_or_file.write(xmlstr)
        filename_or_file.close()
716554
private XmlDocument makeDocument(String name, String document)
            throws XmlException, PolicyIndexException {
        Map<String, String> metadata =
                m_utils.getDocumentMetadata(document
                        .getBytes());
        XmlDocument doc = m_dbXmlManager.manager.createDocument();
        String docName = name;

        if (docName == null || docName.isEmpty()) {
            docName = metadata.get("PolicyId");
        }

        if (docName == null || docName.isEmpty()) {
            throw new PolicyIndexException("Could not extract PolicyID from document.");
        }

        doc.setMetaData("metadata", "PolicyId", new XmlValue(XmlValue.STRING,
                                                             docName));
        doc.setContent(document);
        doc.setName(docName);

        // FIXME:
        // this is probably redundant as the xpath queries now directly query the policy
        // for the "any" scenarios
        String item = null;
        item = metadata.get("anySubject");
        if (item != null) {
            doc.setMetaData("metadata",
                            "anySubject",
                            new XmlValue(XmlValue.STRING, item));
        }

        item = metadata.get("anyResource");
        if (item != null) {
            doc.setMetaData("metadata",
                            "anyResource",
                            new XmlValue(XmlValue.STRING, item));
        }

        item = metadata.get("anyAction");
        if (item != null) {
            doc.setMetaData("metadata",
                            "anyAction",
                            new XmlValue(XmlValue.STRING, item));
        }

        item = metadata.get("anyEnvironment");
        if (item != null) {
            doc.setMetaData("metadata",
                            "anyEnvironment",
                            new XmlValue(XmlValue.STRING, item));
        }

        return doc;
    }
416168
protected function buildXml()
    {
        $_config =& CKFinder_Connector_Core_Factory::getInstance("Core_Config");
        if (!$this->_currentFolder->checkAcl(CKFINDER_CONNECTOR_ACL_FOLDER_VIEW)) {
            $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_UNAUTHORIZED);
        }

        // Map the virtual path to the local server path.
        $_sServerDir = $this->_currentFolder->getServerPath();

        if (!is_dir($_sServerDir)) {
            $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_FOLDER_NOT_FOUND);
        }

        // Create the "Folders" node.
        $oFoldersNode = new Ckfinder_Connector_Utils_XmlNode("Folders");
        $this->_connectorNode->addChild($oFoldersNode);

        $files = array();
        if ($dh = @opendir($_sServerDir)) {
            while (($file = readdir($dh)) !== false) {
                if ($file != "." && $file != ".." && is_dir($_sServerDir . $file)) {
                    $files[] = $file;
                }
            }
            closedir($dh);
        } else {
            $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_ACCESS_DENIED);
        }

        $resourceTypeInfo = $this->_currentFolder->getResourceTypeConfig();

        if (sizeof($files)>0) {
            natcasesort($files);
            $i=0;
            foreach ($files as $file) {
                $oAcl = $_config->getAccessControlConfig();
                $folderPath = $this->_currentFolder->getClientPath() . $file . "/";
                $aclMask = $oAcl->getComputedMask($this->_currentFolder->getResourceTypeName(), $folderPath);

                if (($aclMask & CKFINDER_CONNECTOR_ACL_FOLDER_VIEW) != CKFINDER_CONNECTOR_ACL_FOLDER_VIEW) {
                    continue;
                }
                if ($resourceTypeInfo->checkIsHiddenFolder($file)) {
                    continue;
                }

                // Create the "Folder" node.
                $oFolderNode[$i] = new Ckfinder_Connector_Utils_XmlNode("Folder");
                $oFoldersNode->addChild($oFolderNode[$i]);
                $oFolderNode[$i]->addAttribute("name", CKFinder_Connector_Utils_FileSystem::convertToConnectorEncoding($file));
                $oFolderNode[$i]->addAttribute("hasChildren", CKFinder_Connector_Utils_FileSystem::hasChildren($folderPath, $resourceTypeInfo) ? "true" : "false");
                $oFolderNode[$i]->addAttribute("acl", $aclMask);

                $i++;
            }
        }
    }