Parses an XML document into a form read for insertion into the database

    xml = the xml document to be parsed
557486
def parse(self,xml):
    
    if not self.xmlparser:
      raise LIGOLwParseError, "pyRXP parser not initialized"
    if not self.lwtparser:
      raise LIGOLwParseError, "LIGO_LW tuple parser not initialized"
    xml = "".join([x.strip() for x in xml.split('\n')])
    ligolwtup = self.xmlparser(xml)
    if self.curs:
      self.lwtparser.unique = UniqueIds(self.curs)
    self.table = self.lwtparser.parsetuple(ligolwtup)
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
852066
public Xml read(String xmlPathQuery, boolean captureContent) {
        XmlPath xmlPath = XmlPathParser.parse(xmlPathQuery);
        Xml doc = new Xml();
        boolean record = false;
        int levelIndex = 0;

        XmlNode node;
        while((node = pullXmlNode()) != null) {
            if(node instanceof XmlStartElement) {
                XmlStartElement startElement = (XmlStartElement) node;
                Element element = new Element(startElement.getLocalName());
                element.addAttributes(startElement.getAttributes());
                currentPath.addLast(element);
                if(xmlPath.matches(currentPath)) {
                    if(!captureContent) {
                        // capture single element only
                        doc.addElement(element);
                        return doc;
                    }
                    // turn on document builder
                    record = true;
                }
                if(record) {
                    // build document
                    doc.addElement(element);
                    levelIndex += 1;
                }
            } else if(node instanceof XmlEndElement) {
                if(xmlPath.isSimplePattern() && levelIndex == 0) {
                    // a simple pattern query can not read further up
                    nodeQueue.push(node);
                    return null;
                }
                if(currentPath.getLast() instanceof Content) {
                    currentPath.removeLast();
                }
                currentPath.removeLast();
                if(record) {
                    // build document
                    doc.endElement();
                    levelIndex -= 1;
                    if(levelIndex == 0) {
                        return doc;
                    }
                }
            } else if(node instanceof XmlContent) {
                XmlContent content = (XmlContent) node;
                if(currentPath.getLast() instanceof Content) {
                    currentPath.removeLast();
                }
                currentPath.addLast(new Content(content.getText()));
                if(record) {
                    // build document
                    doc.addContent(new Content(content.getText()));
                }
            } else {
                // don't know how to handle this type, internal error
                throw new XmlReaderException("Unknown XmlNode type: " + node);
            }
        }
        // no element was found matching the query
        return null;
    }
368599
private Document parseInputSource(InputSource s) throws JspException {
        try {
            DocumentBuilder db = XmlUtil.newDocumentBuilder();
            db.setEntityResolver(entityResolver);
            return db.parse(s);
        } catch (SAXException e) {
            throw new JspException(e);
        } catch (IOException e) {
            throw new JspException(e);
        }
    }
964805
def xml(self):
        
        tree = ElementTree.parse(METADATA_XML_TEMPLATE)
        root = tree.getroot()

        for name, prop in list(self.properties.items()):
            path = prop.xml_path
            elem = root.find(path, XML_NS)
            if elem is None:
                # create elem
                elem = insert_xml_element(root, path)
            elem.text = self.get_xml_value(name)

        return root
953855
def from_xml(self, doc):
        """"""
        import xml.sax
        handler = DomainDumpParser(self)
        xml.sax.parse(doc, handler)
        return handler
621619
def parse(data)
      if data.respond_to?(:read)
        data = data.read
      end

      if data.blank?
        {}
      else
        @dbf = DocumentBuilderFactory.new_instance
        # secure processing of java xml
        # https://archive.is/9xcQQ
        @dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false)
        @dbf.setFeature("http://xml.org/sax/features/external-general-entities", false)
        @dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false)
        @dbf.setFeature(javax.xml.XMLConstants::FEATURE_SECURE_PROCESSING, true)
        xml_string_reader = StringReader.new(data)
        xml_input_source = InputSource.new(xml_string_reader)
        doc = @dbf.new_document_builder.parse(xml_input_source)
        merge_element!({ CONTENT_KEY => "" }, doc.document_element, XmlMini.depth)
      end
    end
992551
@Override
    public String execute(EditXmlInputs inputs) throws Exception {
        Document doc = XmlUtils.createDocument(inputs.getXml(), inputs.getFilePath(), inputs.getParsingFeatures());
        NamespaceContext ctx = XmlUtils.getNamespaceContext(inputs.getXml(), inputs.getFilePath());
        NodeList nodeListToMove = XmlUtils.readNode(doc, inputs.getXpath1(), ctx);
        NodeList nodeListWhereToMove = XmlUtils.readNode(doc, inputs.getXpath2(), ctx);
        Node nodeToMove;
        Node nodeWhereToMove;

        if (!inputs.getXpath2().contains(inputs.getXpath1())) {
            // remove nodes
            for (int i = 0; i < nodeListToMove.getLength(); i++) {
                nodeToMove = nodeListToMove.item(i);
                if (nodeToMove != doc.getDocumentElement()) {
                    nodeToMove.getParentNode().removeChild(nodeToMove);
                }
            }
            //add nodes to designated location
            for (int i = 0; i < nodeListWhereToMove.getLength(); i++) {
                nodeWhereToMove = nodeListWhereToMove.item(i);
                for (int j = 0; j < nodeListToMove.getLength(); j++) {
                    nodeToMove = nodeListToMove.item(j);
                    nodeToMove = doc.importNode(nodeToMove, true);
                    nodeWhereToMove.appendChild(nodeToMove);
                }
            }
        }
        return DocumentUtils.documentToString(doc);
    }
1340311
private function xml() {
    	$document = new DOMDocument('1.0', 'UTF-8');
    	$document->appendChild($this->buildElement($this, $document));
    	return $document;
    }
125794
private Document parseText(String text) throws DocumentException {
        Document result;

        String encoding = getEncoding(text);

        InputSource source = new InputSource(new StringReader(text));
        source.setEncoding(encoding);

        result = reader.read(source);

        // if the XML parser doesn't provide a way to retrieve the encoding,
        // specify it manually
        if (result.getXMLEncoding() == null) {
            result.setXMLEncoding(encoding);
        }

        return result;
    }
1122449
def as_xml(self):
        
        # Build tree
        spacing = ("\n" if (self.pretty_xml) else "")
        root = Element('error', {'xmlns': I3F_NS})
        root.text = spacing
        e_parameter = Element('parameter', {})
        e_parameter.text = self.parameter
        e_parameter.tail = spacing
        root.append(e_parameter)
        if (self.text):
            e_text = Element('text', {})
            e_text.text = self.text
            e_text.tail = spacing
            root.append(e_text)
        # Write out as XML document to return
        tree = ElementTree(root)
        xml_buf = io.BytesIO()
        if (sys.version_info < (2, 7)):
            tree.write(xml_buf, encoding='UTF-8')
        else:
            tree.write(xml_buf, encoding='UTF-8',
                       xml_declaration=True, method='xml')
        return(xml_buf.getvalue().decode('utf-8'))
1253600
def parse_xml(string) #:doc:
      Nokogiri::XML::Document.parse(string) do |opts|
        opts.options = 0
        opts.noblanks
      end
    end
1139193
function xmlString()
    {
        $doc = new DOMDocument( '1.0', 'utf-8' );
        $root = $doc->createElement( "ezmatrix" );
        $doc->appendChild( $root );

        $name = $doc->createElement( "name", $this->Name );
        $root->appendChild( $name );

        $columnsNode = $doc->createElement( "columns" );

        $sequentalColumns = $this->Matrix['columns']['sequential'];
        $columnAmount = $this->NumColumns;
        $columnsNode->setAttribute( 'number', $columnAmount );
        $root->appendChild( $columnsNode );

        if ( $sequentalColumns != null )
        {
            for( $i = 0; $i < $columnAmount; $i++ )
            {
                $column = $sequentalColumns[$i];
                if ( $column != null && $column['identifier'] != 'col_' . ($i+1) )
                {
                    unset( $columnNode );
                    $columnNode = $doc->createElement( 'column' );
                    $columnNode->appendChild( $doc->createTextNode( $column['name'] ) );
                    $columnNode->setAttribute( 'num', $i );
                    $columnNode->setAttribute( 'id', $column['identifier'] );

                    $columnsNode->appendChild( $columnNode );
                }
            }

        }

        $rowsNode =  $doc->createElement( "rows" );
        $rowAmount = $this->NumRows;

        $rowsNode->setAttribute( 'number', $rowAmount );

        $root->appendChild( $rowsNode );

        foreach ( $this->Cells as $cell )
        {
            unset( $cellNode );
            $cellNode = $doc->createElement( 'c' );
            $cellNode->appendChild( $doc->createTextNode( $cell ) );

            $root->appendChild( $cellNode );
        }

        return $this->domString( $doc );
    }
120812
public static Document parseXMLResponse(String xmlStr) {
        if ((xmlStr == null) || (xmlStr.length() == 0)) {
            return null;
        }

        // FIXME: error handling for the DOM parsing...
        try {
            DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            return db.parse(new ByteArrayInputStream(xmlStr.getBytes()));
        } catch (ParserConfigurationException | IOException | SAXException pcex) {
            //ignore
        }

        return null;
    }
384054
private Object parseXmlElement(Element element) {
        if(element.getFirstChild() instanceof Text) {
            Text text = (Text) element.getFirstChild();
            return text.getData();
        }
        return element;
    }
1125259
public static Document parseXmlString(String _xmlStr, boolean _validating, boolean _namespaceAware) throws IOException {

        DocumentBuilderFactory dbFac = DocumentBuilderFactory.newInstance();
        dbFac.setNamespaceAware(_namespaceAware);
        dbFac.setValidating(_validating);

        try {
            return dbFac.newDocumentBuilder().parse(new ByteArrayInputStream(_xmlStr.getBytes(StandardCharsets.UTF_8)));

        } catch (IOException _ex) {
            throw _ex;
        } catch (Exception _ex) {
            throw new IOException("Failed to parse " + StringUtil.abbreviate(_xmlStr, 500), _ex);
        }

    }
69235
public static Document parseFile(final File input) {
        Document output = null;
        try {
            final DocumentBuilder db = FACTORY.newDocumentBuilder();
            db.setErrorHandler(new ParserErrorHandler());
            output = db.parse(input);
        } catch (final Exception ex) {
            String msg = "Problem parsing the input XML file";
            if (ex instanceof SAXParseException) {
                msg += " at line #" + ((SAXParseException) ex).getLineNumber();
            }
            LOGGER.error(msg, ex);
        }

        return output;
    }