Open the XML document, check for the DocBook5 namespace and finally
 apply Xinclude tretement to it, if it has a XInclude namespace.
 Returns a map with the file name, the file's modification time, and the section structure.
353225
def analyze_file
     full_name = File.expand_path(@source)
     changed  = File.mtime(@source)
     @doc = XML::Document.file(@source)
     raise ArgumentError, "Error: #{@source} is apparently not DocBook 5." unless is_docbook?(@doc)
     @doc.xinclude if has_xinclude?(@doc)
     sections = analyze_document(@doc)
     {:file => full_name, :modified => changed, :sections => sections}
   end
891811
def xcworkspace_element_start_xml(depth, elem)
      attributes = case elem.name
                   when 'Group'
                     %w(location name)
                   when 'FileRef'
                     %w(location)
                   end
      contents = "<#{elem.name}"
      indent = '   ' * depth
      attributes.each { |name| contents += "\n   #{name} = \"#{elem.attribute(name)}\"" }
      contents.split("\n").map { |line| "#{indent}#{line}" }.join("\n") + ">\n"
    end
987509
def isRef(self, doc, attr):
        
        if doc is None: doc__o = None
        else: doc__o = doc._o
        if attr is None: attr__o = None
        else: attr__o = attr._o
        ret = libxml2mod.xmlIsRef(doc__o, self._o, attr__o)
        return ret
75900
private synchronized Document asXmlDocument() throws IOException {
    Document doc;
    try {
      doc =
        DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    } catch (ParserConfigurationException pe) {
      throw new IOException(pe);
    }
    Element conf = doc.createElement("configuration");
    doc.appendChild(conf);
    conf.appendChild(doc.createTextNode("\n"));
    handleDeprecation(); //ensure properties is set and deprecation is handled
    for (Enumeration<Object> e = properties.keys(); e.hasMoreElements();) {
      String name = (String)e.nextElement();
      Object object = properties.get(name);
      String value = null;
      if (object instanceof String) {
        value = (String) object;
      }else {
        continue;
      }
      Element propNode = doc.createElement("property");
      conf.appendChild(propNode);

      Element nameNode = doc.createElement("name");
      nameNode.appendChild(doc.createTextNode(name));
      propNode.appendChild(nameNode);

      Element valueNode = doc.createElement("value");
      valueNode.appendChild(doc.createTextNode(value));
      propNode.appendChild(valueNode);

      if (updatingResource != null) {
        String[] sources = updatingResource.get(name);
        if(sources != null) {
          for(String s : sources) {
            Element sourceNode = doc.createElement("source");
            sourceNode.appendChild(doc.createTextNode(s));
            propNode.appendChild(sourceNode);
          }
        }
      }

      conf.appendChild(doc.createTextNode("\n"));
    }
    return doc;
  }
1024554
public Document getDocument(String xmlFilename) throws CmsXmlException {

        // try to get it from the cache
        Document document = m_cache.get(xmlFilename);

        if (document == null) {
            try {
                document = CmsXmlUtils.unmarshalHelper(
                    new InputSource(new FileReader(getFile(xmlFilename))),
                    NO_ENTITY_RESOLVER);
            } catch (FileNotFoundException e) {
                LOG.error("Could not read file " + xmlFilename, e);
                throw new CmsXmlException(new CmsMessageContainer(null, e.toString()));

            } catch (Exception e) {
                LOG.error("Could not parse file " + xmlFilename, e);
                throw new CmsXmlException(
                    Messages.get().container(Messages.ERR_XML_COULD_NOT_PARSE_FILE_1, xmlFilename),
                    e);
            }
            // cache the doc
            m_cache.put(xmlFilename, document);
        }
        return document;
    }
970158
function XPathEngine() {
// public
    this.doc = null;

    /**
     * Returns whether the current runtime environment supports the use of this
     * engine. Needs override.
     */
    this.isAvailable = function() { return false; };

    /**
     * Sets the document to be used for evaluation. Always returns the current
     * engine object so as to be chainable.
     */
    this.setDocument = function(newDocument) {
        this.doc = newDocument;
        return this;
    };

    /**
     * Returns a possibly-empty list of nodes. Needs override.
     */
    this.selectNodes = function(xpath, contextNode, namespaceResolver) {
        return [];
    };

    /**
     * Returns a single node, or null if no nodes were selected. This default
     * implementation simply returns the first result of selectNodes(), or
     * null.
     */
    this.selectSingleNode = function(xpath, contextNode, namespaceResolver) {
        var nodes = this.selectNodes(xpath, contextNode, namespaceResolver);
        return (nodes.length > 0 ? nodes[0] : null);
    };

    /**
     * Returns the number of matching nodes. This default implementation simply
     * returns the length of the result of selectNodes(), which should be
     * adequate for most sub-implementations.
     */
    this.countNodes = function(xpath, contextNode, namespaceResolver) {
        return this.selectNodes(xpath, contextNode, namespaceResolver).length;
    };

    /**
     * An optimization; likely to be a no-op for many implementations. Always
     * returns the current engine object so as to be chainable.
     */
    this.setIgnoreAttributesWithoutValue = function(ignore) { return this; };
}
239402
def __xinclude_lxml(target, source, env):
    
    from lxml import etree
    
    doc = etree.parse(str(source[0]))
    doc.xinclude()
    try:
        doc.write(str(target[0]), xml_declaration=True, 
                  encoding="UTF-8", pretty_print=True)
    except:
        pass

    return None
950027
def LookupNamespace(self, prefix):
        
        ret = libxml2mod.xmlTextReaderLookupNamespace(self._o, prefix)
        return ret
1328795
def updateObjectFromXML(xml_doc, obj, mapping):
    
    nsmap = None
    if isinstance(mapping, dict):
        # The special key @namespaces is used to pass
        # namespaces and prefix mappings for xpath selectors.
        # e.g. {'x': 'http://example.com/namespace'}
        if '@namespaces' in mapping:
            nsmap = mapping['@namespaces']
    else:
        raise TypeError('Tag-to-property map must be a dict.')
    # Iterate over the keys of the translation dictionary from event objects
    # to xml objects, so we can update the fields with the new information
    for k, v in mapping.items():
        if k.startswith('@'):
            continue
        selected_text = None
        if isinstance(v, basestring):
            selector = v
        elif isinstance(v, list):
            selector = '/'.join(v)
        else:
            raise TypeError(
                'Invalid tag-to-property mapping dict: '
                'values must be strings or lists, not %s.' % (type(v),)
            )
        try:
            selected_text = xml_doc.xpath(selector, namespaces=nsmap)
            if isinstance(selected_text, list):
                selected_text = selected_text[0]
            selected_text = selected_text.text
            setattr(obj, k, selected_text)
        except IndexError:
            # Assume the value is missing. It's also possible that the
            # given selector is valid but wrong, but the more common
            # case is that the element is missing. To be consistent with
            # the prior implementation, empty resultsets just mean empty
            # attributes.
            continue
    return obj
239671
def newDocFragment(self):
        
        ret = libxml2mod.xmlNewDocFragment(self._o)
        if ret is None:raise treeError('xmlNewDocFragment() failed')
        __tmp = xmlNode(_obj=ret)
        return __tmp
739514
@SuppressWarnings("rawtypes")
	private Document buildTimeMLDocument(JCas jcas, Dct dct, String filename) {
		DocumentBuilderFactory dbf = null;
		DocumentBuilder db = null;
		Document doc = null;
		
		try {
			dbf = DocumentBuilderFactory.newInstance();
			dbf.setNamespaceAware(true);
			db = dbf.newDocumentBuilder();
			doc = db.newDocument();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
			Logger.printError(component, "XML Builder could not be instantiated");
		}
		
		// create the TimeML root element
		Element rootEl = doc.createElement("TimeML");
		rootEl.setAttributeNS("xmlns", "xsi", "http://www.w3.org/2001/XMLSchema-instance");
		rootEl.setAttributeNS("xsi", "noNamespaceSchemaLocation", "http://timeml.org/timeMLdocs/TimeML_1.2.1.xsd");
		doc.appendChild(rootEl);
		
		// create DOCID tag
		Element docidEl = doc.createElement("DOCID");
		docidEl.appendChild(doc.createTextNode(filename));
		rootEl.appendChild(docidEl);
		
		// create DCT tag
		if(dct != null) {
			Element dctEl = doc.createElement("DCT");
	
			Element timexForDCT = doc.createElement("TIMEX3");
			timexForDCT.setAttribute("tid", "t0");
			timexForDCT.setAttribute("type", "DATE");
			timexForDCT.setAttribute("value", dct.getValue());
			timexForDCT.setAttribute("temporalFunction", "false");
			timexForDCT.setAttribute("functionInDocument", "CREATION_TIME");
			timexForDCT.appendChild(doc.createTextNode(dct.getValue()));
			
			dctEl.appendChild(timexForDCT); // NEW		
			rootEl.appendChild(dctEl);
		}
		
		// create and fill the TEXT tag
		Integer offset = 0;
		Element textEl = doc.createElement("TEXT");
		rootEl.appendChild(textEl);
		
		FSIterator it = jcas.getAnnotationIndex(Timex3.type).iterator();
		// if there are no timexes, just add one text node as a child. otherwise, iterate through timexes
		String docText = jcas.getDocumentText();
		if(!it.hasNext()) {
			textEl.appendChild(doc.createTextNode(docText));
		} else {
			HashSet<Timex3> timexesToSkip = new HashSet<Timex3>();
			Timex3 prevT = null;
			Timex3 thisT = null;
			// iterate over timexes to find overlaps
			while(it.hasNext()) {
				thisT = (Timex3) it.next();
				
				if((Class) thisT.getClass() != (Class) Timex3.class) // disregard types that inherit from Timex3
					continue;
				
				// check for whether this and the previous timex overlap. ex: [early (friday] morning)
				if(prevT != null && prevT.getEnd() > thisT.getBegin()) {
					
					Timex3 removedT = null; // only for debug message
					// assuming longer value string means better granularity
					if(prevT.getTimexValue().length() > thisT.getTimexValue().length()) {
						timexesToSkip.add(thisT);
						removedT = thisT;
						/* prevT stays the same. */
					} else {
						timexesToSkip.add(prevT);
						removedT = prevT;
						prevT = thisT; // this iteration's prevT was removed; setting for new iteration 
					}
					
					Logger.printError(component, "Two overlapping Timexes have been discovered:" + System.getProperty("line.separator")
							+ "Timex A: " + prevT.getCoveredText() + " [\"" + prevT.getTimexValue() + "\" / " + prevT.getBegin() + ":" + prevT.getEnd() + "]" 
							+ System.getProperty("line.separator")
							+ "Timex B: " + removedT.getCoveredText() + " [\"" + removedT.getTimexValue() + "\" / " + removedT.getBegin() + ":" + removedT.getEnd() + "]" 
							+ " [removed]" + System.getProperty("line.separator")
							+ "The writer chose, for granularity: " + prevT.getCoveredText() + System.getProperty("line.separator")
							+ "This usually happens with an incomplete ruleset. Please consider adding "
							+ "a new rule that covers the entire expression.");
				} else { // no overlap found? set current timex as next iteration's previous timex
					prevT = thisT;
				}
			}
			
			it.moveToFirst(); // reset iterator for another loop
			// iterate over timexes to write the DOM tree.
			while(it.hasNext()) {
				Timex3 t = (Timex3) it.next();
				if((Class) t.getClass() != (Class) Timex3.class) // disregard types that inherit from Timex3
					continue;
				
				// if this timex was marked to be removed, skip it entirely and go to the next one.
				if(timexesToSkip.contains(t))
					continue;
				
				if(t.getBegin() > offset) { 
					// add a textnode that contains the text before the timex
					textEl.appendChild(doc.createTextNode(docText.substring(offset, t.getBegin())));
				}
				
				// create the TIMEX3 element
				Element newTimex = doc.createElement("TIMEX3");
				
				// set its required attributes
				newTimex.setAttribute("tid", t.getTimexId());
				newTimex.setAttribute("type", t.getTimexType());
				newTimex.setAttribute("value", t.getTimexValue());
				
				// set its optional attributes
				if(!t.getTimexMod().equals(""))
					newTimex.setAttribute("mod", t.getTimexMod());
				if(!t.getTimexQuant().equals(""))
					newTimex.setAttribute("quant", t.getTimexQuant());
				if(!t.getTimexFreq().equals(""))
					newTimex.setAttribute("freq", t.getTimexFreq());
				
				// set text
				newTimex.appendChild(doc.createTextNode(t.getCoveredText()));
				
				// add the timex tag to the text tag
				textEl.appendChild(newTimex);
				
				// set cursor to the end of the timex
				offset = t.getEnd();
			}
			
			// append the rest of the document text
			if(offset < docText.length())
				textEl.appendChild(doc.createTextNode(docText.substring(offset)));
		}
		
		return doc;
	}
560299
def documento(self, *args, **kwargs):
        
        forcar_unicode = kwargs.pop('forcar_unicode', False)
        incluir_xml_decl = kwargs.pop('incluir_xml_decl', True)
        doc = ET.tostring(self._xml(*args, **kwargs),
                encoding='utf-8').decode('utf-8')
        if forcar_unicode:
            if incluir_xml_decl:
                doc = u'{}\n{}'.format(constantes.XML_DECL_UNICODE, doc)
        else:
            if incluir_xml_decl:
                doc = '{}\n{}'.format(constantes.XML_DECL, unidecode(doc))
            else:
                doc = unidecode(doc)
        return doc
1346983
def docCopyNode(self, doc, extended):
        
        if doc is None: doc__o = None
        else: doc__o = doc._o
        ret = libxml2mod.xmlDocCopyNode(self._o, doc__o, extended)
        if ret is None:raise treeError('xmlDocCopyNode() failed')
        __tmp = xmlNode(_obj=ret)
        return __tmp
1269744
private String readNamespaceAttr(Document doc) {

    	// lazy loading is mostly pointless but it keeps things together
    	if (namespaceExpr == null) {
    		namespaceExpr = initNamespaceAttrExpression();
    	}

		String s;
		try {
			s = namespaceExpr.evaluate(doc);
		} catch (XPathExpressionException e) {
			throw new PluginException("Error evaluating namespace XPath expression: " + e, e);
		}
		// xpath returns an empty string if not found, null is cleaner for callers
		return (s == null || s.length() == 0) ? null : s;
    }
636880
def parseCatalogFile(filename):
    
    ret = libxml2mod.xmlParseCatalogFile(filename)
    if ret is None:raise parserError('xmlParseCatalogFile() failed')
    return xmlDoc(_obj=ret)
387962
private void includeXmlContent(final XIncludeAttributes xIncludeAttributes)
            throws XIncludeFatalException, XIncludeResourceException
    {
        try
        {
            settingLanguage();
            final SAXSource source = buildingXIncludeSource(xIncludeAttributes);
            final TreeInfo docInfo = this.context.getConfiguration().getProcessor().getUnderlyingConfiguration()
                    .buildDocumentTree(source);
            final XdmNode node = new XdmNode(docInfo.getRootNode());
            startingInjectXInclude();
            injectingXInclude(xIncludeAttributes, source, node);
        }
        catch (final XPointerResourceException e)
        {
            throw new XIncludeResourceException(e.getMessage());
        }
        catch (final XPointerException e)
        {
            throw new XIncludeFatalException(e.getMessage());
        }
        catch (final XPathException e)
        {
            if (e.getCause() instanceof XIncludeFatalException)
            {
                throw (XIncludeFatalException) e.getCause();
            }
            else
            {
                throw new XIncludeFatalException(e.getMessage());
            }
        }
        finally
        {
            if (isInjectingXInclude())
            {
                endingInjectXInclude();
            }
        }
    }
603010
def ns(self):
        
        ret = libxml2mod.xmlNodeGetNs(self._o)
        if ret is None:return None
        __tmp = xmlNs(_obj=ret)
        return __tmp