Try to validate a the root element basically it does the
          following check as described by the XML-1.0 recommendation:
          - [ VC: Root Element Type ] it doesn't try to recurse or
           apply other check to the element
483635
def validateRoot(self, doc):
        
        if doc is None: doc__o = None
        else: doc__o = doc._o
        ret = libxml2mod.xmlValidateRoot(self._o, doc__o)
        return ret
1129047
public static void checkNode(Node node, Node.Type... validTypes) {
		for (Node.Type type : validTypes) {
			if (node.getNodeType() == type) {
				return;
			}
		}
		StringJoiner sj = new StringJoiner(", ");
		for (Node.Type type : validTypes) {
			sj.add(type.toString());
		}
		String nodeName = node.getNodeType().name();
		if (node instanceof NameBearer) {
			nodeName = ((NameBearer) node).getName();
		}
		throw new FuzzerException(nodeName + ": invalid, must be one of " + sj.toString());
	}
950068
public void validateXMLString(String xml, String dtdFile, String docType) throws SAXException, IOException, ParserConfigurationException {
    validateInternal(xml, dtdFile, docType);
  }
462110
def validate(self, formats_dir="../formats/"):
        """"""
        #TODO: download XSD from web
        if self.inline:
            xmlschema = ElementTree.XMLSchema(ElementTree.parse(StringIO("\n".join(open(formats_dir+"dcoi-dsc.xsd").readlines()))))
            xmlschema.assertValid(self.tree)
            #return xmlschema.validate(self)
        else:
            xmlschema = ElementTree.XMLSchema(ElementTree.parse(StringIO("\n".join(open(formats_dir+"dutchsemcor-standalone.xsd").readlines()))))
            xmlschema.assertValid(self.tree)
109591
def validate(self, schema_str, xml_valid):
        
        # TODO: be able to get doc for error given an xsd.
        # Changed path to allow have xsd that are imported by others xsd in the
        # same library, and not call to SAT page each time that is generated
        # a new XML.
        with change_path():
            path = os.path.join(
                os.path.dirname(os.path.realpath(__file__)), 'templates')
            os.chdir(path)
            schema_root = etree.parse(StringIO(schema_str))
            schema = etree.XMLSchema(schema_root)
        try:
            tree = etree.parse(StringIO(xml_valid.encode('UTF-8')))
            schema.assertValid(tree)
        except etree.DocumentInvalid as ups:
            self.ups = ups
        finally:
            if self.ups:
                self.valid = False
            else:
                self.valid = True
            return self.valid
716976
private void addRootElement() {
        if (root instanceof Document) {
            // Get the single element child of the document node.
            // There could be a doctype node and comment nodes that we must skip.
            Element element = DOMHelper.getFirstChildElement(root);
            Assert.notNull(element, "there should be a root element!");
            result.add(element);
        } else {
            Assert.isTrue(root instanceof Element, "root must be a document or element node!");
            result.add(root);
        }
    }
827387
def validatePopElement(self, ctxt, elem, qname):
        
        if ctxt is None: ctxt__o = None
        else: ctxt__o = ctxt._o
        if elem is None: elem__o = None
        else: elem__o = elem._o
        ret = libxml2mod.xmlValidatePopElement(ctxt__o, self._o, elem__o, qname)
        return ret
1014308
def validate_element(self, value):
        
        # If value is str is it considered valid.  Satisfies "required=True".
        if isinstance(value, bytes):
            try:
                six.text_type(value, 'UTF-8')
            except UnicodeDecodeError as err:
                try:
                    _ = self.name
                except AttributeError:
                    validation_error = ValidationError(
                        'Field encountered non-UTF-8 string %r: %s' % (value,
                                                                       err))
                else:
                    validation_error = ValidationError(
                        'Field %s encountered non-UTF-8 string %r: %s' % (
                            self.name, value, err))
                    validation_error.field_name = self.name
                raise validation_error
        else:
            return super(StringField, self).validate_element(value)
        return value
633198
private void validateVeLogNode(VeLogNode node) {
    if (node.getVeDataExpression().getRoot().getType().getKind() != Kind.VE_DATA) {
      reporter.report(
          node.getVeDataExpression().getSourceLocation(),
          INVALID_VE,
          node.getVeDataExpression().getRoot().getType());
    }
    if (node.getLogonlyExpression() != null) {
      // check to see if it is in a msg node.  logonly is disallowed in msg nodes because we don't
      // have an implementation strategy.
      if (isInMsgNode(node)) {
        reporter.report(node.getLogonlyExpression().getSourceLocation(), LOGONLY_DISALLOWED_IN_MSG);
      }
      SoyType type = node.getLogonlyExpression().getType();
      if (type.getKind() != Kind.BOOL) {
        reporter.report(
            node.getLogonlyExpression().getSourceLocation(),
            WRONG_TYPE,
            BoolType.getInstance(),
            type);
      }
    }
  }
293593
private void  g(Attributes attributes) throws SVGParseException
   {
      debug("<g>");

      if (currentElement == null)
         throw new SVGParseException("Invalid document. Root element must be <svg>");
      SVG.Group  obj = new SVG.Group();
      obj.document = svgDocument;
      obj.parent = currentElement;
      parseAttributesCore(obj, attributes);
      parseAttributesStyle(obj, attributes);
      parseAttributesTransform(obj, attributes);
      parseAttributesConditional(obj, attributes);
      currentElement.addChild(obj);
      currentElement = obj;
   }
484908
function isValidElement(o) {
  return (
    typeof HTMLElement === "object" ? o instanceof HTMLElement : //DOM2
      o && typeof o === "object" && o !== null && o.nodeType === 1 && typeof o.nodeName==="string" && o.nodeName.toLowerCase() === 'a-entity'
  );
}
1216524
def _validate_node_name(self, var_value):
        """"""
        # pylint: disable=R0201
        var_values = var_value if isinstance(var_value, list) else [var_value]
        for item in var_values:
            if (not isinstance(item, str)) or (
                isinstance(item, str)
                and (
                    (" " in item)
                    or any(
                        [
                            element.strip() == ""
                            for element in item.strip().split(self._node_separator)
                        ]
                    )
                )
            ):
                return True
        return False
1118061
public final void validate() {
    this.accept(new TreeVisitor() {
      @Override
      public boolean preVisit(TreeNode node) {
        node.validateInner();
        return true;
      }
    });
  }
203031
private void validateElement(List<ValidationMessage> errors, StructureDefinition profile, ElementDefinition definition, StructureDefinition cprofile, ElementDefinition context,
			WrapperElement resource, WrapperElement element, String actualType, NodeStack stack, boolean inCodeableConcept) throws FHIRException {
		element.setDefinition(definition);
		element.setProfile(profile);

    // irrespective of what element it is, it cannot be empty
    if (element.isXml()) {
      rule(errors, IssueType.INVALID, element.line(), element.col(), stack.getLiteralPath(), FormatUtilities.FHIR_NS.equals(element.getNamespace()),
          "Namespace mismatch - expected '" + FormatUtilities.FHIR_NS + "', found '" + element.getNamespace() + "'");
      rule(errors, IssueType.INVALID, element.line(), element.col(), stack.getLiteralPath(), !element.hasNamespace("http://www.w3.org/2001/XMLSchema-instance"),
          "Schema Instance Namespace is not allowed in instances");
      rule(errors, IssueType.INVALID, element.line(), element.col(), stack.getLiteralPath(), !element.hasProcessingInstruction(), "No Processing Instructions in resources");
    }
    rule(errors, IssueType.INVALID, element.line(), element.col(), stack.getLiteralPath(), !empty(element), "Elements must have some content (@value, extensions, or children elements)");

		checkInvariants(errors, stack.literalPath, profile, definition, null, null, resource, element);

    // get the list of direct defined children, including slices
    List<ElementDefinition> childDefinitions = ProfileUtilities.getChildMap(profile, definition.getName(), definition.getPath(), definition.getNameReference());

    // 1. List the children, and remember their exact path (convenience)
    List<ElementInfo> children = new ArrayList<InstanceValidator.ElementInfo>();
    ChildIterator iter = new ChildIterator(stack.getLiteralPath(), element);
    while (iter.next())
      children.add(new ElementInfo(iter.name(), iter.element(), iter.path(), iter.count()));

    // 2. assign children to a definition
    // for each definition, for each child, check whether it belongs in the slice
    ElementDefinition slice = null;
    for (ElementDefinition ed : childDefinitions) {
      boolean process = true;
      // where are we with slicing
      if (ed.hasSlicing()) {
        if (slice != null && slice.getPath().equals(ed.getPath()))
					throw new DefinitionException("Slice encountered midway through path on " + slice.getPath());
        slice = ed;
        process = false;
      } else if (slice != null && !slice.getPath().equals(ed.getPath()))
        slice = null;

      if (process) {
        for (ElementInfo ei : children) {
          boolean match = false;
          if (slice == null) {
            match = nameMatches(ei.name, tail(ed.getPath()));
          } else {
            if (nameMatches(ei.name, tail(ed.getPath())))
              match = sliceMatches(ei.element, ei.path, slice, ed, profile);
          }
          if (match) {
            if (rule(errors, IssueType.INVALID, ei.line(), ei.col(), ei.path, ei.definition == null, "Element matches more than one slice"))
              ei.definition = ed;
          }
        }
      }
    }
    for (ElementInfo ei : children)
      if (ei.path.endsWith(".extension"))
        rule(errors, IssueType.INVALID, ei.line(), ei.col(), ei.path, ei.definition != null, "Element is unknown or does not match any slice (url=\"" + ei.element.getAttribute("url") + "\")");
      else
        rule(errors, IssueType.INVALID, ei.line(), ei.col(), ei.path, (ei.definition != null) || (!ei.element.isXml() && ei.element.getName().equals("fhir_comments")),
            "Element is unknown or does not match any slice");

    // 3. report any definitions that have a cardinality problem
    for (ElementDefinition ed : childDefinitions) {
      if (ed.getRepresentation().isEmpty()) { // ignore xml attributes
        int count = 0;
        for (ElementInfo ei : children)
          if (ei.definition == ed)
            count++;
        if (ed.getMin() > 0) {
          rule(errors, IssueType.STRUCTURE, element.line(), element.col(), stack.getLiteralPath(), count >= ed.getMin(),
              "Element '" + stack.getLiteralPath() + "." + tail(ed.getPath()) + "': minimum required = " + Integer.toString(ed.getMin()) + ", but only found " + Integer.toString(count));
        }
        if (ed.hasMax() && !ed.getMax().equals("*")) {
          rule(errors, IssueType.STRUCTURE, element.line(), element.col(), stack.getLiteralPath(), count <= Integer.parseInt(ed.getMax()),
              "Element " + tail(ed.getPath()) + " @ " + stack.getLiteralPath() + ": max allowed = " + ed.getMax() + ", but found " + Integer.toString(count));
        }

      }
    }
    // 4. check order if any slices are orderd. (todo)

    // 5. inspect each child for validity
    for (ElementInfo ei : children) {
      if (ei.definition != null) {
        String type = null;
        ElementDefinition typeDefn = null;
        if (ei.definition.getType().size() == 1 && !ei.definition.getType().get(0).getCode().equals("*") && !ei.definition.getType().get(0).getCode().equals("Element")
            && !ei.definition.getType().get(0).getCode().equals("BackboneElement"))
          type = ei.definition.getType().get(0).getCode();
        else if (ei.definition.getType().size() == 1 && ei.definition.getType().get(0).getCode().equals("*")) {
          String prefix = tail(ei.definition.getPath());
          assert prefix.endsWith("[x]");
          type = ei.name.substring(prefix.length() - 3);
          if (isPrimitiveType(type))
            type = Utilities.uncapitalize(type);
        } else if (ei.definition.getType().size() > 1) {

          String prefix = tail(ei.definition.getPath());
          assert typesAreAllReference(ei.definition.getType()) || prefix.endsWith("[x]") : prefix;

          prefix = prefix.substring(0, prefix.length() - 3);
          for (TypeRefComponent t : ei.definition.getType())
            if ((prefix + Utilities.capitalize(t.getCode())).equals(ei.name))
              type = t.getCode();
          if (type == null) {
            TypeRefComponent trc = ei.definition.getType().get(0);
            if (trc.getCode().equals("Reference"))
              type = "Reference";
            else 
              rule(errors, IssueType.STRUCTURE, ei.line(), ei.col(), stack.getLiteralPath(), false,
                  "The element " + ei.name + " is illegal. Valid types at this point are " + describeTypes(ei.definition.getType()));
          }
        } else if (ei.definition.getNameReference() != null) {
          typeDefn = resolveNameReference(profile.getSnapshot(), ei.definition.getNameReference());
        }

        if (type != null) {
          if (type.startsWith("@")) {
            ei.definition = findElement(profile, type.substring(1));
            type = null;
          }
        }
        NodeStack localStack = stack.push(ei.element, ei.count, ei.definition, type == null ? typeDefn : resolveType(type));
        String localStackLiterapPath = localStack.getLiteralPath();
        String eiPath = ei.path;
        assert(eiPath.equals(localStackLiterapPath)) : "ei.path: " + ei.path + "  -  localStack.getLiterapPath: " + localStackLiterapPath;
        boolean thisIsCodeableConcept = false;

        if (type != null) {
          if (isPrimitiveType(type))
            checkPrimitive(errors, ei.path, type, ei.definition, ei.element);
          else {
            if (type.equals("Identifier"))
              checkIdentifier(errors, ei.path, ei.element, ei.definition);
            else if (type.equals("Coding"))
              checkCoding(errors, ei.path, ei.element, profile, ei.definition, inCodeableConcept);
            else if (type.equals("CodeableConcept")) {
              checkCodeableConcept(errors, ei.path, ei.element, profile, ei.definition);
              thisIsCodeableConcept = true;
            } else if (type.equals("Reference"))
              checkReference(errors, ei.path, ei.element, profile, ei.definition, actualType, localStack);
            
            if (type.equals("Extension"))
              checkExtension(errors, ei.path, ei.element, ei.definition, profile, localStack);
            else if (type.equals("Resource"))
							validateContains(errors, ei.path, ei.definition, definition, resource, ei.element, localStack, idStatusForEntry(element, ei)); // if
            // (str.matches(".*([.,/])work\\1$"))
            else {
              StructureDefinition p = getProfileForType(type);
              if (rule(errors, IssueType.STRUCTURE, ei.line(), ei.col(), ei.path, p != null, "Unknown type " + type)) {
								validateElement(errors, p, p.getSnapshot().getElement().get(0), profile, ei.definition, resource, ei.element, type, localStack, thisIsCodeableConcept);
              }
            }
          }
        } else {
          if (rule(errors, IssueType.STRUCTURE, ei.line(), ei.col(), stack.getLiteralPath(), ei.definition != null, "Unrecognised Content " + ei.name))
						validateElement(errors, profile, ei.definition, null, null, resource, ei.element, type, localStack, false);
				}
			}
		}
	}
1075744
private void processElement(Element element) {
    context.setCurrentSegment(element);
    currentProp = null;
    currentAttribute = null;

    // Process attributes
    boolean shouldPopContext = processElementAttributes(element);

    // Process text segments
    StreamSupport
        .stream(((Iterable<Segment>) element::getNodeIterator).spliterator(), false)
        .filter(segment -> !(segment instanceof Tag)
            && !(segment instanceof CharacterReference))
        .filter(segment -> {
          for (Element child : element.getChildElements()) {
            if (child.encloses(segment)) {
              return false;
            }
          }
          return true;
        })
        .forEach(this::processTextNode);

    // Recurse downwards
    element.getChildElements().
        forEach(this::processElement);

    // After downward recursion, pop the context layer if necessary
    if (shouldPopContext) {
      context.popContextLayer();
    }
  }
837378
def is_root(self, el):
        

        root = self.root and self.root is el
        if not root:
            parent = self.get_parent(el)
            root = parent is not None and self.is_html and self.is_iframe(parent)
        return root
706687
def _check_for_errors(etree: ET.ElementTree):
    """"""
    if etree.getroot().tag == 'error':
        raise APIError(etree.getroot().text)