Uploads XML from nominatim.openstreetmap.org, parses it, and  create DummyItems from it
765302
private List<DummyItem> loadXmlFromNetwork(String urlString) throws IOException {
        String jString;
        // Instantiate the parser
        List<Entry> entries = null;
        List<DummyItem> rtnArray = new ArrayList<DummyItem>();
        BufferedReader streamReader = null;
        try {
            streamReader = new BufferedReader(downloadUrl(urlString));
            StringBuilder responseStrBuilder = new StringBuilder();

            String inputStr;
            while ((inputStr = streamReader.readLine()) != null)
                responseStrBuilder.append(inputStr);
            jString = responseStrBuilder.toString();
            if (jString == null) {
                Log.e(SamplesApplication.TAG, "Nominatim Webpage: request failed for "
                        + urlString);
                return new ArrayList<DummyItem>(0);
            }
            JSONArray jPlaceIds = new JSONArray(jString);
            int n = jPlaceIds.length();
            entries = new ArrayList<Entry>(n);
            for (int i = 0; i < n; i++) {
                JSONObject jPlace = jPlaceIds.getJSONObject(i);
                Entry poi = new Entry(
                        jPlace.optLong("place_id"),
                        jPlace.getString("osm_type"),
                        jPlace.getString("osm_id"),
                        // jPlace.getString("place_rank"),
                        jPlace.getString("boundingbox"),
                        jPlace.getString("lat"),
                        jPlace.getString("lon"),
                        jPlace.getString("display_name"),
                        jPlace.getString("class"),
                        jPlace.getString("type"),
                        jPlace.getString("importance"));
                entries.add(poi);
            }
        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        } finally {
            if (streamReader != null) {
                streamReader.close();
            }
        }

        // StackOverflowXmlParser returns a List (called "entries") of Entry objects.
        // Each Entry object represents a single place in the XML searchresult.
        // This section processes the entries list to create a 'DummyItem' from each entry.
        for (Entry entry : entries) {
            rtnArray.add(
                    new DummyItem(entry.mOsm_id,
                            entry.mDisplay_name.split(",")[0],
                            new LatLong(Double.parseDouble(entry.mLat), Double.parseDouble(entry.mLon)),
                            entry.mDisplay_name));
        }
        return rtnArray;
    }
1214481
private static void parseXMLAttributes(NamedNodeMap attrMap, List<UNode> childUNodeList) {
        for (int index = 0; index < attrMap.getLength(); index++) {
            Attr attr = (Attr)attrMap.item(index);
            UNode childNode = createValueNode(attr.getName(), attr.getValue(), true);
            childUNodeList.add(childNode);
        }
    }
1008440
private static Document createSurroundingXMLResp() throws ParserConfigurationException {
        final Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
        return document;
    }
1161372
function(doc) {
        if (typeof doc == "string") { 
            doc = OpenLayers.Format.XML.prototype.read.apply(this, [doc]);
        }

        /* Try RSS items first, then Atom entries */
        var itemlist = null;
        itemlist = this.getElementsByTagNameNS(doc, '*', 'item');
        if (itemlist.length == 0) {
            itemlist = this.getElementsByTagNameNS(doc, '*', 'entry');
        }
        
        var numItems = itemlist.length;
        var features = new Array(numItems);
        for(var i=0; i<numItems; i++) {
            features[i] = this.createFeatureFromItem(itemlist[i]);
        }
        return features;
    }
131472
function resourceToXml (resource, rel, currentIndent, nextIndent) {
    // Do not add line feeds if no indentation is asked
    var LF = (currentIndent || nextIndent) ? '\n' : '';

    // Resource tag
    var xml = currentIndent + '<resource';

    // Resource attributes: rel, href, name
    if (rel) xml += ' rel="' + escapeXml(rel) + '"';
    if (resource.href || resource._links.self) xml += ' href="' + escapeXml(resource.href || resource._links.self.href) + '"';
    if (resource.name) xml += ' name="' + escapeXml(resource.name) + '"';
    xml += '>' + LF;

    // Add <link> tags
    for (var rel in resource._links) {
      if (!resource.href && rel === 'self') continue;
      xml += currentIndent + nextIndent + resource._links[rel].toXML() + LF;
    }

    // Add embedded
    for (var embed in resource._embedded) {
      // [Naive singularize](https://github.com/naholyr/js-hal#why-this-crappy-singularplural-management%E2%80%AF)
      var rel = embed.replace(/s$/, '');
      resource._embedded[embed].forEach(function (res) {
        xml += resourceToXml(res, rel, currentIndent + nextIndent, currentIndent + nextIndent + nextIndent) + LF;
      });
    }

    // Add properties as tags
    for (var prop in resource) {
      if (resource.hasOwnProperty(prop) && prop !== '_links' && prop !== '_embedded') {
        xml += currentIndent + nextIndent + '<' + prop + '>' + String(resource[prop]) + '</' + prop + '>' + LF;
      }
    }

    // Close tag and return the shit
    xml += currentIndent + '</resource>';

    return xml;
  }
542353
def fromFile(filename):
        
        xdata = None
        ydata = None

        # try parsing an XML file
        try:
            xdata = ElementTree.parse(filename).getroot()
        except StandardError:
            xdata = None

        if xdata is None:
            # try parsing a yaml file
            if yaml:
                with open(filename, 'r') as f:
                    text = f.read()

                try:
                    ydata = yaml.load(text)
                except StandardError:
                    return None
            else:
                log.warning('Could not process yaml builder!')

        # load a yaml definition
        if type(ydata) == dict:
            typ = ydata.get('type')
            module = ydata.get('module')
            builder = Builder.plugin(typ, module)
            if builder:
                return builder.fromYaml(ydata, os.path.dirname(filename))
            else:
                log.warning('Could not find builder: {0}'.format(typ))

        # load an xml definition
        elif xdata is not None:
            typ = xdata.get('type')
            module = xdata.get('module')
            builder = Builder.plugin(typ, module)
            if builder:
                return builder.fromXml(xdata, os.path.dirname(filename))
            else:
                log.warning('Could not find builder: {0}'.format(typ))

        return None
414008
def from_file(cls, file_path, validate=True):
        
        return xmlmap.load_xmlobject_from_file(file_path, xmlclass=cls, validate=validate)
1326919
def schemaNewParserCtxt(URL):
    
    ret = libxml2mod.xmlSchemaNewParserCtxt(URL)
    if ret is None:raise parserError('xmlSchemaNewParserCtxt() failed')
    return SchemaParserCtxt(_obj=ret)
98985
def anyxml(self, node, elem, module, path):
        """"""
        nel, newm, path = self.sample_element(node, elem, module, path)
        if path is None:
            return
        if self.annots:
            nel.append(etree.Comment(" anyxml "))
117334
def transform(odtfile, debug=False, parsable=False, outputdir=None):
    
    # Store mapping of images extracted from the ODT file (and their bits)
    images = {}
    # Log of Errors and Warnings generated
    # For example, the text produced by XSLT should be:
    # {'level':'WARNING',
    #  'msg'  :'Headings without text between them are not allowed',
    #  'id'   :'import-auto-id2376'}
    # That way we can put a little * near all the cnxml where issues arose
    errors = []

    zip = zipfile.ZipFile(odtfile, 'r')
    content = zip.read('content.xml')
    xml = etree.fromstring(content)

    def appendLog(xslDoc):
        if hasattr(xslDoc, 'error_log'):
            for entry in xslDoc.error_log:
                # Entries are of the form:
                # {'level':'ERROR','id':'id1234','msg':'Descriptive message'}
                text = entry.message
                try:
                    dict = json.loads(text)
                    errors.append(dict)
                except ValueError:
                    errors.append({
                      u'level':u'CRITICAL',
                      u'id'   :u'(none)',
                      u'msg'  :unicode(text) })
                    
    def injectStyles(xml):
        # HACK - need to find the object location from the manifest ...
        strStyles = zip.read('styles.xml')
        
        parser = etree.XMLParser()
        parser.feed(strStyles)
        stylesXml = parser.close()
        
        for i, obj in enumerate(STYLES_XPATH(stylesXml)):
          xml.append(obj)

        return xml


    # All MathML is stored in separate files "Object #/content.xml"
    # This converter includes the MathML by looking up the file in the zip
    def mathIncluder(xml):
        for i, obj in enumerate(MATH_XPATH(xml)):
            strMathPath = MATH_HREF_XPATH(obj)[0] # Or obj.get('{%s}href' % XLINK_NS)
            if strMathPath[0] == '#':
                strMathPath = strMathPath[1:]
            # Remove leading './' Zip doesn't like it
            if strMathPath[0] == '.':
                strMathPath = strMathPath[2:]

            # HACK - need to find the object location from the manifest ...
            strMathPath = os.path.join(strMathPath, 'content.xml')
            strMath = zip.read(strMathPath)
            
            #parser = etree.XMLParser(encoding='utf-8')
            #parser.feed(strMath)
            #math = parser.close()
            math = etree.parse(StringIO(strMath)).getroot()
            
            # Replace the reference to the Math with the actual MathML
            obj.getparent().replace(obj, math)
        return xml

    def imagePuller(xml):
        for i, obj in enumerate(IMAGE_XPATH(xml)):
            strPath = IMAGE_HREF_XPATH(obj)[0]
            strName = IMAGE_NAME_XPATH(obj)[0]

            fileNeedEnding = ( strName.find('.') == -1 )
            if fileNeedEnding:
                strName = strName + strPath[strPath.index('.'):]

            if strPath[0] == '#':
                strPath = strPath[1:]
            # Remove leading './' Zip doesn't like it
            if strPath[0] == '.':
                strPath = strPath[2:]

            image = zip.read(strPath)
            images[strName] = image
            
            # Later on, an XSL pass will convert the draw:frame to a c:image and 
            # set the @src correctly

        return xml
        
    def drawPuller(xml):
        styles = DRAW_STYLES_XPATH(xml)
                       
        empty_odg_dirname = os.path.join(dirname, 'empty_odg_template')
        
        temp_dirname = tempfile.mkdtemp()
            
        for i, obj in enumerate(DRAW_XPATH(xml)):
            # Copy everything except content.xml from the empty ODG (OOo Draw) template into a new zipfile
            
            odg_filename = DRAW_FILENAME_PREFIX + str(i) + '.odg'
            png_filename = DRAW_FILENAME_PREFIX + str(i) + '.png'

            # add PNG filename as attribute to parent node. The good thing is: The child (obj) will get lost! :-)
            parent = obj.getparent()
            parent.attrib['ooo_drawing'] = png_filename
            
            odg_zip = zipfile.ZipFile(os.path.join(temp_dirname, odg_filename), 'w', zipfile.ZIP_DEFLATED)
            for root, dirs, files in os.walk(empty_odg_dirname):
                for name in files:
                    if name not in ('content.xml', 'styles.xml'):   # copy everything inside ZIP except content.xml or styles.xml
                        sourcename = os.path.join(root, name)
                        # http://stackoverflow.com/a/1193171/756056                        
                        arcname = os.path.join(root[len(empty_odg_dirname):], name)  # Path name inside the ZIP file, empty_odg_template is the root folder
                        odg_zip.write(sourcename, arcname)
            
            content = etree.parse(os.path.join(empty_odg_dirname, 'content.xml'))
                           
            # Inject content styles in empty OOo Draw content.xml
            content_style_xpath = etree.XPath('/office:document-content/office:automatic-styles', namespaces=NAMESPACES)
            content_styles = content_style_xpath(content)                                
            for style in styles:
                content_styles[0].append(deepcopy(style))
            
            # Inject drawing in empty OOo Draw content.xml
            content_page_xpath = etree.XPath('/office:document-content/office:body/office:drawing/draw:page', namespaces=NAMESPACES)
            content_page = content_page_xpath(content)
            content_page[0].append(obj)
            
            # write modified content.xml
            odg_zip.writestr('content.xml', etree.tostring(content, xml_declaration=True, encoding='UTF-8'))
            
            # copy styles.xml from odt to odg without modification
            styles_xml = zip.read('styles.xml')
            odg_zip.writestr('styles.xml', styles_xml)

            odg_zip.close()
            
            # TODO: Better error handling in the future.
            try:
                # convert every odg to png
                command = '/usr/bin/soffice -headless -nologo -nofirststartwizard "macro:///Standard.Module1.SaveAsPNG(%s,%s)"' % (os.path.join(temp_dirname, odg_filename),os.path.join(temp_dirname, png_filename))
                os.system(command)

                # save every image to memory            
                image = open(os.path.join(temp_dirname, png_filename), 'r').read()
                images[png_filename] = image
                
                if outputdir is not None:
                    shutil.copy (os.path.join(temp_dirname, odg_filename), os.path.join(outputdir, odg_filename))
                    shutil.copy (os.path.join(temp_dirname, png_filename), os.path.join(outputdir, png_filename))
            except:
                pass
                
        # delete temporary directory
        shutil.rmtree(temp_dirname)
        
        return xml

    # Reparse after XSL because the RED-escape pass injects arbitrary XML
    def redParser(xml):
        xsl = makeXsl('pass1_odt2red-escape.xsl')
        result = xsl(xml)
        appendLog(xsl)
        try:
            xml = etree.fromstring(etree.tostring(result))
        except etree.XMLSyntaxError, e:
            msg = str(e)
            xml = makeXsl('pass1_odt2red-failed.xsl')(xml, message="'%s'" % msg.replace("'", '"'))
            xml = xml.getroot()
        return xml

    def replaceSymbols(xml):
        xmlstr = etree.tostring(xml)
        xmlstr = symbols.replace(xmlstr)
        return etree.fromstring(xmlstr)

    PIPELINE = [
      drawPuller, # gets OOo Draw objects out of odt and generate odg (OOo Draw) files
      replaceSymbols,
      injectStyles, # include the styles.xml file because it contains list numbering info
      makeXsl('pass2_odt-normalize.xsl'), # This needs to be done 2x to fix headings       
      makeXsl('pass2_odt-normalize.xsl'), # In the worst case all headings are 9 
                            # and need to be 1. See (testbed) southwood__Lesson_2.doc
      makeXsl('pass2_odt-collapse-spans.xsl'), # Collapse adjacent spans (for RED)
      redParser, # makeXsl('pass1_odt2red-escape.xsl'),
      makeXsl('pass4_odt-headers.xsl'),
      imagePuller, # Need to run before math because both have a <draw:image> (see xpath)
      mathIncluder,
      makeXsl('pass7_odt2cnxml.xsl'),
      makeXsl('pass8_cnxml-cleanup.xsl'),
      makeXsl('pass8.5_cnxml-cleanup.xsl'),
      makeXsl('pass9_id-generation.xsl'),
      makeXsl('pass10_processing-instruction-logger.xsl'),
      ]

    # "xml" variable gets replaced during each iteration
    passNum = 0
    for xslDoc in PIPELINE:
        if debug: errors.append("DEBUG: Starting pass %d" % passNum)
        xml = xslDoc(xml)

        appendLog(xslDoc)
        if outputdir is not None: writeXMLFile(os.path.join(outputdir, 'pass%d.xml' % passNum), xml)
        passNum += 1

    # In most cases (EIP) Invalid XML is preferable over valid but Escaped XML
    if not parsable:
      xml = (makeXsl('pass11_red-unescape.xsl'))(xml)

    return (xml, images, errors)
1215112
public void toXML(XMLBuilder xml) throws IllegalArgumentException {
        assert xml != null;
        
        // Determine what tag name to use for the generated element. 
        Map<String, String> attrMap = new LinkedHashMap<>(); 
        String elemName = m_name;
        if (m_tagName.length() > 0) {
            // Place m_name into a "name" attribute and use m_tagName
            attrMap.put("name", m_name);
            elemName = m_tagName;
        }
        
        // Add child VALUE nodes marked as "attribute" in its own map.
        addXMLAttributes(attrMap);
        switch (m_type) {
        case ARRAY:
            // Start an element with or without attributes.
            if (attrMap.size() > 0) {
                xml.startElement(elemName, attrMap);
            } else {
                xml.startElement(elemName);
            }
            
            // Add XML for non-attribute child nodes.
            if (m_children != null) {
                for (UNode childNode : m_children) {
                    if (childNode.m_type != NodeType.VALUE || !childNode.m_bAttribute) {
                        childNode.toXML(xml);
                    }
                }
            }
            xml.endElement();
            break;
        case MAP:
            // Start an element with or without attributes.
            if (attrMap.size() > 0) {
                xml.startElement(elemName, attrMap);
            } else {
                xml.startElement(elemName);
            }
            
            // Add XML for non-attribute child nodes in name order.
            if (m_childNodeMap != null) {
                assert m_childNodeMap.size() == m_children.size();
                for (UNode childNode : m_childNodeMap.values()) {
                    if (childNode.m_type != NodeType.VALUE || !childNode.m_bAttribute) {
                        childNode.toXML(xml);
                    }
                }
            }
            xml.endElement();
            break;
        case VALUE:
            // Map to a simple element.
            String value = m_value;
            if (Utils.containsIllegalXML(value)) {
                value = Utils.base64FromString(m_value);
                attrMap.put("encoding", "base64");
            }
            if (attrMap.size() > 0) {
                xml.addDataElement(elemName, value, attrMap);
            } else {
                xml.addDataElement(elemName, value);
            }
            break;
        default:
            assert false : "Unexpected NodeType: " + m_type;
        }
    }
566792
def _create_xml_node(cls):
        
        try:
            xml_map = cls._xml_map
        except AttributeError:
            raise ValueError("This model has no XML definition")

        return _create_xml_node(
            xml_map.get('name', cls.__name__),
            xml_map.get("prefix", None),
            xml_map.get("ns", None)
        )
155680
def addObjectFromXML(xmlObject, XMLToObjectFunc,
                     topLevelName, idKey, updateList):
    

    # Get the current object to update
    contentElement = getNodeByName(xmlObject, "content")
    objectNode = getNodeByName(contentElement, topLevelName)
    dupObjects = None
    newObject = XMLToObjectFunc(objectNode)
    try:
        kwargs = {idKey: getattr(newObject, idKey)}
        dupObjects = type(newObject).objects.filter(**kwargs)
    except type(newObject).DoesNotExist:
        pass
    if dupObjects and dupObjects.count() > 1:
        raise Exception(
            "Duplicate object with identifier %s" % getattr(newObject, idKey)
        )
    newObject.save()
    return newObject
492718
def getItemXML():
    ''' '''
    xml=""
    for item in range(NUM_GOALS):
        x = str(random.randint(old_div(-ARENA_WIDTH,2),old_div(ARENA_WIDTH,2)))
        z = str(random.randint(old_div(-ARENA_BREADTH,2),old_div(ARENA_BREADTH,2)))
        xml += '''<DrawItem x="''' + x + '''" y="210" z="''' + z + '''" type="''' + GOAL_TYPE + '''"/>'''
    return xml
1364407
def decode(data):
    
    dom = None
    try:
        dom = dhtmlparser.parseString(data)
    except Exception, e:
        raise MetaParsingException("Can't parse your XML data: %s" % e.message)

    root = dom.find("root")

    # check whether there is <root>s
    if not root:
        raise MetaParsingException("All elements have to be inside <root>.")

    # and make sure, that there is not too many <root>s
    if len(root) > 1:
        raise MetaParsingException("Too many <root> elements in your XML!")

    items = root[0].find("item")

    # check for items
    if not items:
        raise MetaParsingException("There are no <items> in your XML <root>!")

    decoded = []
    for item in items:
        if "key" not in item.params:
            raise MetaParsingException(
                "There is no 'key' parameter in %s." % str(item)
            )

        decoded.append([
            item.params["key"],
            item.getContent().strip()
        ])

    decoded = validator.check_structure(decoded)

    return decoded
193085
def nodeToXML(nodeObject):
    

    xmlRoot = etree.Element(NODE + "node", nsmap=NODE_NSMAP)
    nameNode = etree.SubElement(xmlRoot, NODE + "name")
    nameNode.text = nodeObject.node_name
    urlNode = etree.SubElement(xmlRoot, NODE + "url")
    urlNode.text = nodeObject.node_url
    pathNode = etree.SubElement(xmlRoot, NODE + "path")
    pathNode.text = nodeObject.node_path
    capNode = etree.SubElement(xmlRoot, NODE + "capacity")
    capNode.text = str(nodeObject.node_capacity)
    sizeNode = etree.SubElement(xmlRoot, NODE + "size")
    sizeNode.text = str(nodeObject.node_size)
    if nodeObject.last_checked:
        checkedNode = etree.SubElement(xmlRoot, NODE + "lastChecked")
        checkedNode.text = nodeObject.last_checked.strftime(TIME_FORMAT_STRING)
    return xmlRoot
110463
def pp_xml(body):
    """"""
    pretty = xml.dom.minidom.parseString(body)
    return pretty.toprettyxml(indent="  ")