parse an XML file and build a tree. Automatic support for
      ZLIB/Compress compressed document is provided by default if
      found at compile-time. In the case the document is not Well
       Formed, it attempts to build a tree anyway
559776
def recoverFile(filename):
    
    ret = libxml2mod.xmlRecoverFile(filename)
    if ret is None:raise treeError('xmlRecoverFile() failed')
    return xmlDoc(_obj=ret)
1284293
function toNLCST(tree, file, Parser, options) {
  var settings = options || {}
  var parser

  // Warn for invalid parameters.
  if (!tree || !tree.type) {
    throw new Error('mdast-util-to-nlcst expected node')
  }

  if (!file || !file.messages) {
    throw new Error('mdast-util-to-nlcst expected file')
  }

  // Construct parser.
  if (!Parser) {
    throw new Error('mdast-util-to-nlcst expected parser')
  }

  if (
    !tree.position ||
    !tree.position.start ||
    !tree.position.start.column ||
    !tree.position.start.line
  ) {
    throw new Error('mdast-util-to-nlcst expected position on nodes')
  }

  parser = 'parse' in Parser ? Parser : new Parser()

  // Transform mdast into NLCST tokens, and pass these into `parser.parse` to
  // insert sentences, paragraphs where needed.
  return parser.parse(
    one(
      {
        doc: String(file),
        location: vfileLocation(file),
        parser: parser,
        ignore: ignore.concat(settings.ignore || []),
        source: source.concat(settings.source || [])
      },
      tree
    )
  )
}
617900
private Document prepareTBXDocument() throws ParserConfigurationException {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		Document tbxDocument = builder.newDocument();

		Element martif = tbxDocument.createElement("martif");
		martif.setAttribute("type", "TBX");
		tbxDocument.appendChild(martif);

		Element header = tbxDocument.createElement("martifHeader");
		martif.appendChild(header);

		Element fileDesc = tbxDocument.createElement("fileDesc");
		header.appendChild(fileDesc);

		Element encodingDesc = tbxDocument.createElement("encodingDesc");
		header.appendChild(encodingDesc);

		Element encodingP = tbxDocument.createElement("p");
		encodingP.setAttribute("type", "XCSURI");
		encodingP.setTextContent("http://ttc-project.googlecode.com/files/ttctbx.xcs");
		encodingDesc.appendChild(encodingP);

		Element sourceDesc = tbxDocument.createElement("sourceDesc");
		Element p = tbxDocument.createElement("p");
//		p.setTextContent(workingDir.getAbsolutePath());
		sourceDesc.appendChild(p);
		fileDesc.appendChild(sourceDesc);

		Element text = tbxDocument.createElement("text");
		martif.appendChild(text);

        Element body = tbxDocument.createElement("body");
		text.appendChild(body);
		return tbxDocument;
    }
434745
def parsexml(Class, node, doc, **kwargs): #pylint: disable=bad-classmethod-argument
        

        assert issubclass(Class, AbstractElement)

        if doc.preparsexmlcallback:
            result = doc.preparsexmlcallback(node)
            if not result:
                return None
            if isinstance(result, AbstractElement):
                return result



        dcoi = node.tag.startswith('{' + NSDCOI + '}')
        args = []
        if not kwargs: kwargs = {}
        text = None #for dcoi support
        if (Class.TEXTCONTAINER or Class.PHONCONTAINER) and node.text:
            args.append(node.text)


        for subnode in node: #pylint: disable=too-many-nested-blocks
            #don't trip over comments
            if isinstance(subnode, ElementTree._Comment): #pylint: disable=protected-access
                if (Class.TEXTCONTAINER or Class.PHONCONTAINER) and subnode.tail:
                    args.append(subnode.tail)
            else:
                if subnode.tag.startswith('{' + NSFOLIA + '}'):
                    if doc.debug >= 1: print("[PyNLPl FoLiA DEBUG] Processing subnode " + subnode.tag[nslen:],file=stderr)
                    try:
                        e = doc.parsexml(subnode, Class)
                    except ParseError as e:
                        raise #just re-raise deepest parseError
                    except Exception as e:
                        #Python 3 will preserve full original traceback, Python 2 does not, original cause is explicitly passed to ParseError anyway:
                        raise ParseError("FoLiA exception in handling of <" + subnode.tag[len(NSFOLIA)+2:] + "> @ line " + str(subnode.sourceline) + ": [" + e.__class__.__name__ + "] " + str(e), cause=e)
                    if e is not None:
                        args.append(e)
                    if (Class.TEXTCONTAINER or Class.PHONCONTAINER) and subnode.tail:
                        args.append(subnode.tail)
                elif subnode.tag.startswith('{' + NSDCOI + '}'):
                    #Dcoi support
                    if Class is Text and subnode.tag[nslendcoi:] == 'body':
                        for subsubnode in subnode:
                            if doc.debug >= 1: print("[PyNLPl FoLiA DEBUG] Processing DCOI subnode " + subnode.tag[nslendcoi:],file=stderr)
                            e = doc.parsexml(subsubnode, Class)
                            if e is not None:
                                args.append(e)
                    else:
                        if doc.debug >= 1: print( "[PyNLPl FoLiA DEBUG] Processing DCOI subnode " + subnode.tag[nslendcoi:],file=stderr)
                        e = doc.parsexml(subnode, Class)
                        if e is not None:
                            args.append(e)
                elif doc.debug >= 1:
                    print("[PyNLPl FoLiA DEBUG] Ignoring subnode outside of FoLiA namespace: " + subnode.tag,file=stderr)



        if dcoi:
            dcoipos = dcoilemma = dcoicorrection = dcoicorrectionoriginal = None
        for key, value in node.attrib.items():
            if key[0] == '{' or key =='XMLid':
                if key == '{http://www.w3.org/XML/1998/namespace}id' or key == 'XMLid':
                    key = 'id'
                elif key.startswith( '{' + NSFOLIA + '}'):
                    key = key[nslen:]
                    if key == 'id':
                        #ID in FoLiA namespace is always a reference, passed in kwargs as follows:
                        key = 'idref'
                elif Class.XLINK and key.startswith('{http://www.w3.org/1999/xlink}'):
                    key = key[30:]
                    if key != 'href':
                        key = 'xlink' + key #xlinktype, xlinkrole, xlinklabel, xlinkshow, etc..
                elif key.startswith('{' + NSDCOI + '}'):
                    key = key[nslendcoi:]

            #D-Coi support:
            if dcoi:
                if Class is Word and key == 'pos':
                    dcoipos = value
                    continue
                elif Class is Word and  key == 'lemma':
                    dcoilemma = value
                    continue
                elif Class is Word and  key == 'correction':
                    dcoicorrection = value #class
                    continue
                elif Class is Word and  key == 'original':
                    dcoicorrectionoriginal = value
                    continue
                elif Class is Gap and  key == 'reason':
                    key = 'class'
                elif Class is Gap and  key == 'hand':
                    key = 'annotator'
                elif Class is Division and  key == 'type':
                    key = 'cls'

            kwargs[key] = value

        #D-Coi support:
        if dcoi and TextContent in Class.ACCEPTED_DATA and node.text:
            text = node.text.strip()

            kwargs['text'] = text
            if not AnnotationType.TOKEN in doc.annotationdefaults:
                doc.declare(AnnotationType.TOKEN, set='http://ilk.uvt.nl/folia/sets/ilktok.foliaset')

        if doc.debug >= 1: print("[PyNLPl FoLiA DEBUG] Found " + node.tag[nslen:],file=stderr)
        instance = Class(doc, *args, **kwargs)
        #if id:
        #    if doc.debug >= 1: print >>stderr, "[PyNLPl FoLiA DEBUG] Adding to index: " + id
        #    doc.index[id] = instance
        if dcoi:
            if dcoipos:
                if not AnnotationType.POS in doc.annotationdefaults:
                    doc.declare(AnnotationType.POS, set='http://ilk.uvt.nl/folia/sets/cgn-legacy.foliaset')
                instance.append( PosAnnotation(doc, cls=dcoipos) )
            if dcoilemma:
                if not AnnotationType.LEMMA in doc.annotationdefaults:
                    doc.declare(AnnotationType.LEMMA, set='http://ilk.uvt.nl/folia/sets/mblem-nl.foliaset')
                instance.append( LemmaAnnotation(doc, cls=dcoilemma) )
            if dcoicorrection and dcoicorrectionoriginal and text:
                if not AnnotationType.CORRECTION in doc.annotationdefaults:
                    doc.declare(AnnotationType.CORRECTION, set='http://ilk.uvt.nl/folia/sets/dcoi-corrections.foliaset')
                instance.correct(generate_id_in=instance, cls=dcoicorrection, original=dcoicorrectionoriginal, new=text)

        if doc.parsexmlcallback:
            result = doc.parsexmlcallback(instance)
            if not result:
                return None
            if isinstance(result, AbstractElement):
                return result

        return instance
354184
def load(opts)
      doc = nil
      if(opts.has_key?(:file)) then
        File.open(opts[:file], "rb") { |fd| doc = Nokogiri::XML::Document.parse(fd, nil, nil, Nokogiri::XML::ParseOptions::NOBLANKS|Nokogiri::XML::ParseOptions::NOENT) }
      else
        doc = Nokogiri::XML::Document.parse(opts[:data], nil, nil, Nokogiri::XML::ParseOptions::NOBLANKS|Nokogiri::XML::ParseOptions::NOENT)
      end

      if doc
        root = doc.root.children.first
        return import_xml(root)
      end
    rescue Nokogiri::XML::SyntaxError => e
      raise CFFormatError.new('invalid XML: ' + e.message)
    end
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
545101
protected function buildXml()
  {
    parent::buildXml();

    $extractDir = ( !empty($_POST['extractDir']) ) ? ltrim($_POST['extractDir'],'/') : '';
    $extractDir = CKFinder_Connector_Utils_FileSystem::convertToFilesystemEncoding($extractDir);
    if ( preg_match(CKFINDER_REGEX_INVALID_PATH, $extractDir) ){
      $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_INVALID_REQUEST);
    }
    $extractPath = CKFinder_Connector_Utils_FileSystem::combinePaths($this->_currentFolder->getServerPath(), $extractDir.'/');
    $extractClientPath = CKFinder_Connector_Utils_FileSystem::combinePaths($this->_currentFolder->getClientPath(),$extractDir);
    // acl for upload dir
    $_aclConfig = $this->_config->getAccessControlConfig();
    $aclMask = $_aclConfig->getComputedMask($this->_currentFolder->getResourceTypeName(),$extractDir);

    if ( !(($aclMask & CKFINDER_CONNECTOR_ACL_FOLDER_CREATE ) == CKFINDER_CONNECTOR_ACL_FOLDER_CREATE ) ){
      $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_UNAUTHORIZED);
    }
    if ( empty( $_POST['force']) && file_exists($extractPath) && is_dir($extractPath) && !CKFinder_Connector_Utils_FileSystem::isEmptyDir($extractPath) )
    {
      $dirExists = new CKFinder_Connector_Utils_XmlNode("FolderExists");
      $oErrorNode = new CKFinder_Connector_Utils_XmlNode("Folder");
      $oErrorNode->addAttribute("name", $extractDir);
      $dirExists->addChild($oErrorNode);
      $this->_connectorNode->addChild($dirExists);
      return;
    }
    elseif ( !empty( $_POST['force']) && $_POST['force'] =='overwrite' )
    {
      if ( !(($aclMask &  CKFINDER_CONNECTOR_ACL_FILE_UPLOAD | CKFINDER_CONNECTOR_ACL_FILE_DELETE ) ==  CKFINDER_CONNECTOR_ACL_FILE_UPLOAD | CKFINDER_CONNECTOR_ACL_FILE_DELETE ) ){
        $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_UNAUTHORIZED);
      }
      if ( $extractDir && file_exists($extractPath) && is_dir($extractPath) )
      {
        if ( !(($aclMask &  CKFINDER_CONNECTOR_ACL_FOLDER_CREATE | CKFINDER_CONNECTOR_ACL_FOLDER_DELETE ) ==  CKFINDER_CONNECTOR_ACL_FOLDER_CREATE | CKFINDER_CONNECTOR_ACL_FOLDER_DELETE ) ){
          $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_UNAUTHORIZED);
        }
        if (!CKFinder_Connector_Utils_FileSystem::unlink($extractPath))
        {
            $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_ACCESS_DENIED);
        }
      }
    }
    else if ( !empty( $_POST['force']) && $_POST['force'] !== 'merge' )
    {
      $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_INVALID_REQUEST);
    }

    for ($i = 0; $i < $this->zip->numFiles; $i++)
    {
      $fileName = $this->zip->getNameIndex($i);
      $filePathInfo = pathinfo($fileName);

      $sFileName = $this->checkOneFile( $filePathInfo, $fileName );
      // security test failed, add to skipped
      if ( $sFileName )
      {
        $this->extractTo($extractPath,$extractClientPath,$filePathInfo,$sFileName,$fileName);
      }
    }
    $this->zip->close();


    $this->_connectorNode->addChild($this->unzippedNodes);

    if ($this->errorCode != CKFINDER_CONNECTOR_ERROR_NONE) {
      $this->_connectorNode->addChild($this->skippedFilesNode);
      $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_ZIP_FAILED);
    }
  }
944623
def main_from_xml(file)
      xml_data = File.read(file)
      xml_data.force_encoding('utf-8')

      doc = Nokogiri::XML(xml_data)
      doc.elements.first.elements.first
    end
1121113
def _build_toctree_node(parent=None, entries=None, includefiles=None,
                        caption=None):
    
    # Add the toctree's node itself
    subnode = sphinx.addnodes.toctree()
    subnode['parent'] = parent
    subnode['entries'] = entries
    subnode['includefiles'] = includefiles
    subnode['caption'] = caption
    # These values are needed for toctree node types. We don't need/want
    # these to be configurable for module-toctree.
    subnode['maxdepth'] = 1
    subnode['hidden'] = False
    subnode['glob'] = None
    subnode['hidden'] = False
    subnode['includehidden'] = False
    subnode['numbered'] = 0
    subnode['titlesonly'] = False
    return subnode
969141
def build_tree(self, *args, **kwargs):
        """"""
        # Check length #
        assert len(self) > 3
        # Default option #
        algorithm = kwargs.pop(kwargs, None)
        if algorithm is None: algorithm = 'raxml'
        # Dispatch #
        if algorithm is 'raxml':    return self.build_tree_raxml(*args, **kwargs)
        if algorithm is 'fasttree': return self.build_tree_fast(*args, **kwargs)
988340
def __build_lxml(target, source, env):
    
    from lxml import etree
    
    xslt_ac = etree.XSLTAccessControl(read_file=True, 
                                      write_file=True, 
                                      create_dir=True, 
                                      read_network=False, 
                                      write_network=False)
    xsl_style = env.subst('$DOCBOOK_XSL')
    xsl_tree = etree.parse(xsl_style)
    transform = etree.XSLT(xsl_tree, access_control=xslt_ac)
    doc = etree.parse(str(source[0]))
    # Support for additional parameters
    parampass = {}
    if parampass:
        result = transform(doc, **parampass)
    else:
        result = transform(doc)
        
    try:
        of = open(str(target[0]), "wb")
        of.write(of.write(etree.tostring(result, pretty_print=True)))
        of.close()
    except:
        pass

    return None
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"]})
687543
@Override
    public void build() throws DocletException {
        if (writer == null) {
            //Doclet does not support this output.
            return;
        }
        build(layoutParser.parseXML(ROOT), contentTree);
    }
480752
def _parse_xml(self):
        
        import xml.etree.ElementTree as ET
        from os import path
        #This dict has the keys of XML tags that are required in order for the
        #CI server to run the repo. When each one is parsed, we change its value
        #to True and then check that they are all true at the end.
        required = {"testing": False, "wiki": False}
        #Make sure the file exists and then import it as XML and read the values out.
        if path.isfile(self.filepath):
            tree = ET.parse(self.filepath)
            vms("Parsing XML tree from {}.".format(self.filepath), 2)
            root = tree.getroot()
            if root.tag != "cirepo":
                raise ValueError("The root tag in a continuous integration settings XML "
                                 "file should be a <cirepo> tag.")

            self._parse_repo(root)
            for child in root:
                if child.tag == "cron":
                    if self.server is not None:
                        self.server.cron.settings[self.name] = CronSettings(child)
                if child.tag == "testing":
                    self.testing = TestingSettings(child)
                if child.tag == "static":
                    self.static = StaticSettings(child)
                if child.tag == "wiki":
                    self.wiki["user"] = get_attrib(child, "user", "wiki")
                    self.wiki["password"] = get_attrib(child, "password", "wiki")
                    self.wiki["basepage"] = get_attrib(child, "basepage", "wiki")
                if child.tag in required:
                    required[child.tag] = True

            if not all(required.values()):
                tags = ', '.join(["<{}>".format(t) for t in required])
                raise ValueError("{} are required tags in the repo's XML settings file.".format(tags))
814377
def load_xslt(filename=None, xsl=None):
    '''
    '''
    parser = _get_xmlparser()
    if filename is not None:
        xslt_doc = etree.parse(filename, parser=parser)
    if xsl is not None:
        xslt_doc = etree.fromstring(xsl, parser=parser)

    return etree.XSLT(xslt_doc)
379684
def xml(self, fn=None, src='word/document.xml', XMLClass=XML, **params):
        ""
        if src in self.xml_cache: return self.xml_cache[src]
        if src not in self.zipfile.namelist(): return
        x = XMLClass(
                fn=fn or (self.fn and self.fn.replace('.docx', '.xml')) or None,
                root=self.zipfile.read(src))
        self.xml_cache[src] = x
        return x
159706
def htmlReadFile(filename, encoding, options):
    
    ret = libxml2mod.htmlReadFile(filename, encoding, options)
    if ret is None:raise treeError('htmlReadFile() failed')
    return xmlDoc(_obj=ret)