/*
XmlElement is our basic building block. Everything is an XmlElement; even XmlDocument
behaves like an XmlElement by inheriting its attributes and functions.
508020
function XmlElement(tag) {
  // Capture the parser object off of the XmlDocument delegate
  var parser = delegates[delegates.length - 1].parser;

  this.name = tag.name;
  this.attr = tag.attributes || {};
  this.val = "";
  this.children = [];
  this.firstChild = null;
  this.lastChild = null;

  // Assign parse information
  this.line = parser.line;
  this.column = parser.column;
  this.position = parser.position;
  this.startTagPosition = parser.startTagPosition;
}
534175
function( elem, name, isXML ) {
			var ret;
			return isXML ?
				undefined :
				(ret = elem.getAttributeNode( name )) && ret.value !== "" ?
					ret.value :
					null;
		}
1016370
function XmlDocument(xml) {
  xml && (xml = xml.toString().trim());

  if (!xml)
    throw new Error("No XML to parse!");

  // Expose the parser to the other delegates while the parser is running
  this.parser = sax.parser(true); // strict
  addParserEvents(this.parser);

  // We'll use the file-scoped "delegates" var to remember what elements we're currently
  // parsing; they will push and pop off the stack as we get deeper into the XML hierarchy.
  // It's safe to use a global because JS is single-threaded.
  delegates = [this];
  
  this.parser.write(xml);

  // Remove the parser as it is no longer needed and should not be exposed to clients
  delete this.parser;
}
1070117
public void writeEndElement() throws XMLStreamException {
		try {
			this.checkPendingATEvents();
			encoder.encodeEndElement();
		} catch (Exception e) {
			throw new XMLStreamException(e.getLocalizedMessage(), e);
		}
	}
793650
function (xmlNode) {
            if (!xmlNode) {
                return;
            }
            var node = {};
            for (var i = 0; i < xmlNode.childNodes.length; i++) {
                var currNode = xmlNode.childNodes[i];

                // if it's a text node or a CDATA section use the nodeValue directly
                if (currNode.nodeType != 3 && currNode.nodeType != 4) {
                    var name = currNode.nodeName;
                    var count = 0;
                    for (var j = 0; j < xmlNode.childNodes.length; j++) {
                        if (xmlNode.childNodes[j].nodeName == name) {
                            if (++count == 2) {
                                break;
                            }
                        }
                    }
                    var el = this.__parseXmlNode(currNode);
                    if (count == 2) {
                        if (node[name] == null) {
                            node[name] = [];
                        }
                        node[name].push(el);
                    } else {
                        node[name] = el;
                    }

                } else if (xmlNode.childNodes.length == 1) {
                    node = currNode.nodeValue;
                }
            }
            return node;
        }
130536
public static void ensureChildElement(DomXmlElement parentElement, DomXmlElement childElement) {
    Node parent = childElement.unwrap().getParentNode();
    if (parent == null || !parentElement.unwrap().isEqualNode(parent)) {
      throw LOG.elementIsNotChildOfThisElement(childElement, parentElement);
    }
  }
673435
public void startElement(String namespaceURI, String localName,
                             String qName, Attributes atts) throws SAXException {
        trace("startElement:" + localName + "~" + qName);
        Element newElement = createElement(namespaceURI, qName, atts);
        appendNode(newElement);
        currentElement = newElement;
    }
548276
private boolean addPropertyElement(Element element, String elementName, String textContent) {
        Document doc = element.getOwnerDocument();
        Element newElement = doc.createElement(elementName);
        newElement.setTextContent(textContent);
        Text textNode = doc.createTextNode("\n    ");

        NodeList childNodes = element.getChildNodes();
        for (int i = 0, size = childNodes.getLength(); i < size; i++) {
            Node item = childNodes.item(i);
            if (item instanceof Element) {
                Element childElement = (Element) item;
                int value = childElement.getTagName().compareTo(elementName);
                if (value == 0) {
                    return false;
                }
                if (value > 0) {
                    element.insertBefore(textNode, childElement);
                    element.insertBefore(newElement, textNode);
                    return true;
                }
            }
        }
        // lets insert at the end
        element.appendChild(textNode);
        element.appendChild(newElement);
        return true;
    }
320464
function isXML(res) {
  return (res.headers['content-type'] &&
          (/^[a-zA-Z]+\/xml/.test(res.headers['content-type']) ||
           /^[a-zA-Z]+\/[a-zA-Z]+\+xml/.test(res.headers['content-type'])));

}
1111345
function isHTMLElement(o) {
                    var strOwnerDocument = 'ownerDocument';
                    var strHTMLElement = 'HTMLElement';
                    var wnd = o && o[strOwnerDocument] ? (o[strOwnerDocument].parentWindow || window) : window;
                    return (
                        typeof wnd[strHTMLElement] == TYPES.o ? o instanceof wnd[strHTMLElement] : //DOM2
                        o && typeof o == TYPES.o && o !== null && o.nodeType === 1 && typeof o.nodeName == TYPES.s
                    );
                }
666709
@Override
    public void startElement(String namespaceURI, String localName,
            String qName, Attributes atts) throws SAXException {
        try {
            if (XHTML_NS.equals(namespaceURI)) {

                if ("meta".equals(localName)
                        && ((atts.getIndex("", "http-equiv") != -1) || (atts.getIndex(
                                "", "httpequiv") != -1))) {
                    return;
                }

                // start and element name
                this.writer.write('<');
                this.writer.write(localName);

                // attributes
                int length = atts.getLength();
                boolean langPrinted = false;
                for (int i = 0; i < length; i++) {
                    String ns = atts.getURI(i);
                    String name = null;
                    if ("".equals(ns)) {
                        name = atts.getLocalName(i);
                    } else if ("http://www.w3.org/XML/1998/namespace".equals(ns)
                            && "lang".equals(atts.getLocalName(i))) {
                        name = "lang";
                    }
                    if (name != null && !(langPrinted && "lang".equals(name))) {
                        this.writer.write(' ');
                        this.writer.write(name);
                        if ("lang".equals(name)) {
                            langPrinted = true;
                        }
                        if (Arrays.binarySearch(booleanAttributes, name) < 0) {
                            // write value, escape certain characters
                            this.writer.write("=\"");
                            String value = atts.getValue(i);
                            for (int j = 0; j < value.length(); j++) {
                                char c = value.charAt(j);
                                switch (c) {
                                    case '<':
                                        this.writer.write("&lt;");
                                        break;
                                    case '>':
                                        this.writer.write("&gt;");
                                        break;
                                    case '&':
                                        this.writer.write("&amp;");
                                        break;
                                    case '"':
                                        this.writer.write("&quot;");
                                        break;
                                    default:
                                        this.writer.write(c);
                                }
                            }

                            this.writer.write('"');
                        }
                    }
                }

                // close
                this.writer.write('>');
                if (emitMeta && "head".equals(localName)) {
                    this.writer.write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=");
                    this.writer.write(encoding);
                    this.writer.write("\">");
                }
            }
        } catch (IOException ioe) {
            throw (SAXException)new SAXException(ioe).initCause(ioe);
        }
    }
205946
def xml(self, indent = ""):
        """"""
        xml = indent + "<" + self.__class__.__name__
        xml += ' id="'+self.id + '"'
        xml += ' name="'+xmlescape(self.name) + '"'
        xml += ' description="'+xmlescape(self.description) + '"'
        if self.paramflag:
            xml += ' flag="'+self.paramflag + '"'
        for key, v in self.kwargs.items():
            if key not in ('value','error','name','description','flag','paramflag', 'validator'):
                if isinstance(v, bool):
                    xml += ' ' + key + '="' + str(int(v))+ '"'
                elif isinstance(v, list):
                    xml += ' ' + key + '="'+xmlescape(",".join(v))+ '"'
                elif isinstance(v, str)  or ( sys.version < '3' and isinstance(v, unicode)): #pylint: disable=undefined-variable
                    xml += ' ' + key + '="'+xmlescape(v)+ '"'
                else:
                    xml += ' ' + key + '="'+xmlescape(str(v))+ '"'
        if self.hasvalue:
            if sys.version < '3':
                xml += ' value="'+xmlescape(unicode(self.value)) + '"' #pylint: disable=undefined-variable
            else:
                xml += ' value="'+xmlescape(str(self.value)) + '"'
        if self.error:
            xml += ' error="'+xmlescape(self.error) + '"'
        xml += " />"
        return xml
1152584
@Override
  public ScriptElement createScriptElement(Document doc, String source) {
    ScriptElement elem = (ScriptElement) createElement(doc, "script");
    elem.setInnerText(source);
    return elem;
  }
686676
@Override
  protected void marshallElementContent(XMLObject xmlObject, Element domElement) throws MarshallingException {

    // Find out if the our namespace already has been defined, and if so, get the prefix.
    //
    final String namespace = CurrentAddressType.TYPE_NAME.getNamespaceURI();
    Optional<String> _prefix = xmlObject.getNamespaceManager()
      .getNamespaces()
      .stream()
      .filter(n -> namespace.equals(n.getNamespaceURI()))
      .map(n -> n.getNamespacePrefix())
      .findFirst();
    String prefix = _prefix.isPresent() ? _prefix.get() : CurrentAddressType.TYPE_NAME.getPrefix();
    
    StringBuilder sb = new StringBuilder();

    final List<XMLObject> childXMLObjects = xmlObject.getOrderedChildren();
    if (childXMLObjects != null && childXMLObjects.size() > 0) {
      for (final XMLObject childXMLObject : childXMLObjects) {
        if (childXMLObject == null) {
          continue;
        }
        if (!(childXMLObject instanceof XSString)) {
          throw new MarshallingException("Unexpected type of child element - " + childXMLObject.getClass().getName());
        }
        XSString childString = (XSString) childXMLObject;
        if (childString.getValue() == null) {
          continue;
        }
        String localPart = childString.getElementQName().getLocalPart();
        sb.append(String.format("<%s:%s>%s</%s:%s>", prefix, localPart, childString.getValue(), prefix, localPart));
      }
    }
    if (sb.length() > 0) {
      byte[] bytes;
      try {
        bytes = sb.toString().getBytes("UTF-8");
      }
      catch (UnsupportedEncodingException e) {
        throw new MarshallingException(e);
      }
      String base64String = Base64Support.encode(bytes, true);
      ElementSupport.appendTextContent(domElement, base64String);
    }
  }
452765
protected static boolean writeXMLType(Output out, Object xml) {
        log.trace("writeXMLType");
        // If it's a Document write it as Document
        if (xml instanceof Document) {
            writeDocument(out, (Document) xml);
        } else {
            return false;
        }
        return true;
    }
115670
protected void adoptElement(DomXmlElement elementToAdopt) {
    Document document = this.domElement.getOwnerDocument();
    Element element = elementToAdopt.domElement;

    if (!document.equals(element.getOwnerDocument())) {
      Node node = document.adoptNode(element);
      if (node == null) {
        throw LOG.unableToAdoptElement(elementToAdopt);
      }
    }
  }
1280641
function xmlParse(xml) {
    var regex_empty = /\/$/;
    var regex_tagname = xmlCommon.XML10_TAGNAME_REGEXP;
    var regex_attribute = xmlCommon.XML10_ATTRIBUTE_REGEXP;
    if (xml.match(/^<\?xml/)) {
        // When an XML document begins with an XML declaration
        // VersionInfo must appear.
        if (xml.search(new RegExp(xmlCommon.XML10_VERSION_INFO)) === 5) {
            regex_tagname = xmlCommon.XML10_TAGNAME_REGEXP;
            regex_attribute = xmlCommon.XML10_ATTRIBUTE_REGEXP;
        } else if (xml.search(new RegExp(xmlCommon.XML11_VERSION_INFO)) === 5) {
            regex_tagname = xmlCommon.XML11_TAGNAME_REGEXP;
            regex_attribute = xmlCommon.XML11_ATTRIBUTE_REGEXP;
        } else {
            // VersionInfo is missing, or unknown version number.
            // Fall back to XML 1.0 or XML 1.1, or just return null?
            regex_tagname = xmlCommon.XML10_TAGNAME_REGEXP;
            regex_attribute = xmlCommon.XML10_ATTRIBUTE_REGEXP;
        }
    } else {
        // When an XML declaration is missing it's an XML 1.0 document.
        regex_tagname = xmlCommon.XML10_TAGNAME_REGEXP;
        regex_attribute = xmlCommon.XML10_ATTRIBUTE_REGEXP;
    }

    var xmldoc = new XDocument();
    var root = xmldoc;

    // For the record: in Safari, we would create native DOM nodes, but
    // in Opera that is not possible, because the DOM only allows HTML
    // element nodes to be created, so we have to do our own DOM nodes.

    // xmldoc = document.implementation.createDocument('','',null);
    // root = xmldoc; // .createDocumentFragment();
    // NOTE(mesch): using the DocumentFragment instead of the Document
    // crashes my Safari 1.2.4 (v125.12).
    var stack = [];

    var parent = root;
    stack.push(parent);

    // The token that delimits a section that contains markup as
    // content: CDATA or comments.
    var slurp = '';
    var start, end, data, node;
    var x = xmlUtil.stringSplit(xml, '<');
    for ( var i = 1; i < x.length; ++i) {
        var xx = xmlUtil.stringSplit(x[i], '>');
        var tag = xx[0];
        var text = xmlResolveEntities(xx[1] || '');

        if (slurp) {
            // In a "slurp" section (CDATA or comment): only check for the
            // end of the section, otherwise append the whole text.
            end = x[i].indexOf(slurp);
            if (end !== -1) {
                data = x[i].substring(0, end);
                parent.nodeValue += '<' + data;
                stack.pop();
                parent = stack[stack.length - 1];
                text = x[i].substring(end + slurp.length);
                slurp = '';
            } else {
                parent.nodeValue += '<' + x[i];
                text = null;
            }

        } else if (tag.indexOf('![CDATA[') === 0) {
            start = '![CDATA['.length;
            end = x[i].indexOf(']]>');
            if (end !== -1) {
                data = x[i].substring(start, end);
                node = xmldoc.createCDATASection(data);
                parent.appendChild(node);
            } else {
                data = x[i].substring(start);
                text = null;
                node = xmldoc.createCDATASection(data);
                parent.appendChild(node);
                parent = node;
                stack.push(node);
                slurp = ']]>';
            }

        } else if (tag.indexOf('!--') === 0) {
            start = '!--'.length;
            end = x[i].indexOf('-->');
            if (end !== -1) {
                data = x[i].substring(start, end);
                node = xmldoc.createComment(data);
                parent.appendChild(node);
            } else {
                data = x[i].substring(start);
                text = null;
                node = xmldoc.createComment(data);
                parent.appendChild(node);
                parent = node;
                stack.push(node);
                slurp = '-->';
            }

        } else if (tag.charAt(0) === '/') {
            stack.pop();
            parent = stack[stack.length - 1];

        } else if (tag.charAt(0) === '?') {
            // Ignore XML declaration and processing instructions
        } else if (tag.charAt(0) === '!') {
            // Ignore notation and comments
        } else {
            var empty = tag.match(regex_empty);
            var tagname = regex_tagname.exec(tag)[1];
            node = xmldoc.createElement(tagname);

            var att = regex_attribute.exec(tag);
            while (att) {
                var val = xmlResolveEntities(att[5] || att[7] || '');
                node.setAttribute(att[1], val);
                att = regex_attribute.exec(tag);
            }

            parent.appendChild(node);
            if (!empty) {
                parent = node;
                stack.push(node);
            }
        }

        if (text && parent !== root) {
            parent.appendChild(xmldoc.createTextNode(text));
        }
    }

    return root;
}