//protected internal override void configureFactory(DocumentBuilderFactory dbf) //{ // dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA); // dbf.setAttribute(JAXP_SCHEMA_SOURCE, new string[] { ReflectUtil.getResource(DmnModelConstants.DMN_11_SCHEMA_LOCATION, typeof(DmnParser)).ToString(), ReflectUtil.getResource(DmnModelConstants.DMN_11_ALTERNATIVE_SCHEMA_LOCATION, typeof(DmnParser)).ToString() }); // base.configureFactory(dbf); //} protected internal override IModelInstance CreateModelInstance(IDomDocument document) { //var dmnMode = Dmn.INSTANCE.DmnModel as ModelImpl; //var dmnBuilder = Dmn.INSTANCE.DmnModelBuilder; //var t = new DmnModelInstanceImpl(dmnMode, dmnBuilder, document); return(new DmnModelInstanceImpl((ModelImpl)Dmn.Instance.DmnModel, Dmn.Instance.DmnModelBuilder, document)); }
protected internal virtual XmlSchema GetSchema(IDomDocument document) { IDomElement rootElement = document.RootElement; String namespaceURI = rootElement.NamespaceUri; return(schemas[namespaceURI]); }
public IEnumerable <IDomObject> Is(IDomDocument root, IDomObject element) { List <IDomObject> list = new List <IDomObject>(); list.Add(element); return(Select(root, list)); }
public static void WriteDocumentToOutputStream(IDomDocument document, Stream outputStream) { using (TextWriter writer = new StreamWriter(outputStream)) { TransformDocumentToXml(document, writer); } }
// for use during initial construction from char array public void SetTextIndex(IDomDocument dom, int index) { textIndex = index; // create a hard reference to the DOM from which we are mapping our string data. Otherwise if this // is moved to another dom, it will break stringRef = dom; }
public virtual void ValidateModel(IDomDocument document) { XmlSchema schema = GetSchema(document); if (schema == null) { return; } //Validator validator = schema.newValidator(); try { lock (document) { //validator.validate(document.getDomSource()); } } catch (IOException e) { throw new ModelValidationException("Error during DOM document validation", e); } catch (XmlSchemaException e) { throw new ModelValidationException("DOM document is not valid", e); } }
public XmlQName(IDomDocument document, IDomElement element, string namespaceUri, string localName) { this.RootElement = document.RootElement; this.Element = element; this.localName = localName; this.namespaceUri = namespaceUri; this.Prefix = null; }
public virtual IModelElementInstance NewInstance(IModelInstance modelInstance) { ModelInstanceImpl modelInstanceImpl = (ModelInstanceImpl)modelInstance; IDomDocument document = modelInstanceImpl.Document; IDomElement domElement = document.CreateElement(_typeNamespace, _typeName); return(NewInstance(modelInstanceImpl, domElement)); }
/// <summary> /// Converts a <seealso cref="DomDocument"/> to its String representation /// </summary> /// <param name="document"> the XML document to convert </param> public static string ConvertXmlDocumentToString(IDomDocument document) { StringBuilder sb = new StringBuilder(); using (StringWriter writer = new StringWriter(sb)) { TransformDocumentToXml(document, writer); return(sb.ToString()); } }
public void SetDocument(IDomDocument document) { if(_parent == null) { _parentDomElement = document; } else { throw new Exception("Cannot set document for child binders."); } }
//private void ProtectAgainstXxeAttacks() //{ //try //{ // dbf.setFeature("http://xml.org/sax/features/external-general-entities", false); //} //catch (ParserConfigurationException ignored) //{ //} //try //{ // dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); //} //catch (ParserConfigurationException ignored) //{ //} //try //{ // dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false); //} //catch (ParserConfigurationException ignored) //{ //} //dbf.setXIncludeAware(false); //dbf.setExpandEntityReferences(false); //} public virtual IModelInstance ParseModelFromStream(System.IO.Stream inputStream) { IDomDocument document = null; lock (syncObj) { document = DomUtil.ParseInputStream(inputStream); } ValidateModel(document); return(CreateModelInstance(document)); }
/// <summary> /// Return only elements from the sequence that do not match this selector. /// </summary> /// /// <param name="document"> /// The document context. /// </param> /// <param name="sequence"> /// The source sequence. /// </param> /// /// <returns> /// The elements from the source sequence that do not match this selector. /// </returns> public IEnumerable <IDomObject> Except(IDomDocument document, IEnumerable <IDomObject> sequence) { HashSet <IDomObject> matches = new HashSet <IDomObject>(GetFilterSelector().Select(document, sequence)); foreach (var item in sequence) { if (!matches.Contains(item)) { yield return(item); } } }
/// <summary> /// Return only elements from the sequence that do not match this selector. /// </summary> /// /// <param name="document"> /// The document context. /// </param> /// <param name="sequence"> /// The source sequence. /// </param> /// /// <returns> /// The elements from the source sequence that do not match this selector. /// </returns> public IEnumerable <IDomObject> Except(IDomDocument document, IEnumerable <IDomObject> sequence) { return(sequence.Except(Select(document))); //HashSet<IDomObject> matches = new HashSet<IDomObject>(GetFilterSelector().Select(document, sequence)); //foreach (var item in sequence) //{ // if (!matches.Contains(item)) // { // yield return item; // } //} }
public static void TransformDocumentToXml(IDomDocument document, TextWriter writer) { try { //document.DomSource.Declaration.Encoding = Encoding.UTF8.EncodingName; lock (document) { document.DomSource.Save(writer); } } catch (Exception ex) { throw new ModelIoException("Unable to transform model to xml", ex); } }
/// <summary> /// Return only elements of sequence that match this selector. /// </summary> /// /// <param name="document"> /// The DOM to which the members of the sequence belong. /// </param> /// <param name="sequence"> /// The sequence to filter. /// </param> /// /// <returns> /// A sequence of matching elements, which is a subset of the original sequence. /// </returns> public IEnumerable <IDomObject> Filter(IDomDocument document, IEnumerable <IDomObject> sequence) { // This needs to be two steps - returning the selection set directly will cause the sequence // to be ordered in DOM order, and not its original order. HashSet <IDomObject> matches = new HashSet <IDomObject>(ToFilterSelector().Select(document, sequence)); foreach (var item in sequence) { if (matches.Contains(item)) { yield return(item); } } }
/// <summary> /// Updates the cached Document and property flags. /// </summary> /// /// <param name="document"> /// A reference to the owning document. This is also the topmost node in the tree. /// </param> protected void UpdateDocumentFlags(IDomDocument document) { _Document = document; SetDocFlags(); // I think we can get away without resetting children. When removing something from a document, // you are exclusively going to be adding it to something else. We only need to update the parents // during the add operation. if (HasChildren && _Document != null) { foreach (var item in ChildNodes.Cast <DomObject>()) { item.UpdateDocumentFlags(_Document); } } }
void editDom(IDomDocument domDocument) { //increment the serialized range location start only once //to account for extra whitespace we add before the first block m_start.increment(); foreach (List <IDomNode> elements in m_selected) { //insert a whitespace, instead of the 'carriage return' which used to separate the blocks IDomText whitespace = domDocument.createTextNode(" "); m_previous.insert(whitespace); //increment the serialized range location end multiple times //to account for extra whitespace we just added m_end.increment(); IDomNode parent = elements[0].parentNode; //insert each element foreach (IDomNode element in elements) { //remove from current parent before inerting into new parent parent.removeChild(element); //insert into new parent m_previous.insert(element); } if (parent.childNodes.count == 0) { //this block is now empty (all its children removed) //so remove it from the document IDomNode grandparent = parent.parentNode; while (grandparent.childNodes.count == 1) { parent = grandparent; grandparent = grandparent.parentNode; } grandparent.removeChild(parent); } } }
protected internal virtual IList <IDomElement> GetView(ModelElementInstanceImpl referenceSourceParentElement) { IDomDocument document = referenceSourceParentElement.ModelInstance.Document; ICollection <TSource> referenceSourceElements = _referenceSourceCollection.Get <TSource>(referenceSourceParentElement); IList <IDomElement> referenceTargetElements = new List <IDomElement>(); foreach (TSource referenceSourceElement in referenceSourceElements) { string identifier = GetReferenceIdentifier(referenceSourceElement); IDomElement referenceTargetElement = document.GetElementById(identifier); if (referenceTargetElement != null) { referenceTargetElements.Add(referenceTargetElement); } else { throw new ModelException("Unable to find a model element instance for id " + identifier); } } return(referenceTargetElements); }
private ICollection <IDomElement> GetView(IModelElementInstance referenceSourceElement) { IDomDocument document = referenceSourceElement.ModelInstance.Document; string identifier = GetReferenceIdentifier(referenceSourceElement); IList <string> references = StringUtil.SplitListBySeparator(identifier, Separator); ICollection <IDomElement> referenceTargetElements = new List <IDomElement>(); foreach (string reference in references) { //TODO document.getElementById可能获取不到值 IDomElement referenceTargetElement = document.GetElementById(reference); if (referenceTargetElement != null) { referenceTargetElements.Add(referenceTargetElement); } else { throw new ModelException("Unable to find a model element instance for id " + identifier); } } return(referenceTargetElements); }
public CqXmlDocument(IDomDocument document) { //var root = CreateElement("", "ROOT", ""); CqXmlNode docNode = null; foreach (var child in document.ChildNodes) { var node = new CqXmlNode(this, child); if (node.NodeType == XmlNodeType.DocumentType) { this.AppendChild(node); } else { if (docNode == null) { docNode = new CqXmlNode(this, document); this.AppendChild(docNode); } docNode.AppendChild(node); } } }
public CqXmlDocument(IDomDocument document) { //var root = CreateElement("", "ROOT", ""); CqXmlNode docNode=null; foreach (var child in document.ChildNodes) { var node = new CqXmlNode(this, child); if (node.NodeType == XmlNodeType.DocumentType) { this.AppendChild(node); } else { if (docNode == null) { docNode = new CqXmlNode(this, document); this.AppendChild(docNode); } docNode.AppendChild(node); } } }
/// <summary> /// Select from DOM using index. First non-class/tag/id selector will result in this being passed off to GetMatches /// </summary> /// <param name="document"></param> /// <returns></returns> public IEnumerable<IDomObject> Select(IDomDocument document, IEnumerable<IDomObject> context) { if (Selectors == null ) { throw new ArgumentException("No selectors provided."); } if (Selectors.Count == 0) { yield break; } Document = document; IEnumerable<IDomObject> lastResult = null; HashSet<IDomObject> output = new HashSet<IDomObject>(); IEnumerable<IDomObject> selectionSource = context; // Disable the index if there is no context (e.g. disconnected elements) bool useIndex = context.IsNullOrEmpty() || !context.First().IsDisconnected; // Copy the list because it may change during the process ActiveSelectors = new List<Selector>(Selectors); for (activeSelectorId = 0; activeSelectorId < ActiveSelectors.Count; activeSelectorId++) { var selector = ActiveSelectors[activeSelectorId]; CombinatorType combinatorType = selector.CombinatorType; SelectorType selectorType = selector.SelectorType; TraversalType traversalType = selector.TraversalType; // Determine what kind of combining method we will use with previous selection results if (activeSelectorId != 0) { switch (combinatorType) { case CombinatorType.Cumulative: // do nothing break; case CombinatorType.Root: selectionSource = context; if (lastResult != null) { output.AddRange(lastResult); lastResult = null; } break; case CombinatorType.Chained: selectionSource = lastResult; lastResult = null; break; // default (chained): leave lastresult alone } } HashSet<IDomObject> tempResult = null; IEnumerable<IDomObject> interimResult = null; string key = ""; if (useIndex && !selector.NoIndex) { #if DEBUG_PATH if (type.HasFlag(SelectorType.Attribute)) { key = "!" + selector.AttributeName; type &= ~SelectorType.Attribute; if (selector.AttributeValue != null) { InsertAttributeValueSelector(selector); } } else if (type.HasFlag(SelectorType.Tag)) { key = "+"+selector.Tag; type &= ~SelectorType.Tag; } else if (type.HasFlag(SelectorType.ID)) { key = "#" + selector.ID; type &= ~SelectorType.ID; } else if (type.HasFlag(SelectorType.Class)) { key = "." + selector.Class; type &= ~SelectorType.Class; } #else if (selectorType.HasFlag(SelectorType.Attribute)) { key = "!" + (char)DomData.TokenID(selector.AttributeName); selectorType &= ~SelectorType.Attribute; if (selector.AttributeValue != null) { InsertAttributeValueSelector(selector); } } else if (selectorType.HasFlag(SelectorType.Tag)) { key = "+" + (char)DomData.TokenID(selector.Tag, true); selectorType &= ~SelectorType.Tag; } else if (selectorType.HasFlag(SelectorType.ID)) { key = "#" + (char)DomData.TokenID(selector.ID); selectorType &= ~SelectorType.ID; } else if (selectorType.HasFlag(SelectorType.Class)) { key = "." + (char)DomData.TokenID(selector.Class); selectorType &= ~SelectorType.Class; } #endif } // If part of the selector was indexed, key will not be empty. Return initial set from the // index. If any selectors remain after this they will be searched the hard way. if (key != String.Empty) { int depth = 0; bool descendants = true; switch (traversalType) { case TraversalType.Child: depth = selector.ChildDepth; ; descendants = false; break; case TraversalType.Filter: depth = 0; descendants = false; break; case TraversalType.Descendent: depth = 1; descendants = true; break; } if (selectionSource == null) { interimResult = document.QueryIndex(key + DomData.indexSeparator, depth, descendants); } else { interimResult = new HashSet<IDomObject>(); foreach (IDomObject obj in selectionSource) { ((HashSet<IDomObject>)interimResult) .AddRange(document.QueryIndex(key + DomData.indexSeparator + obj.Path, depth, descendants)); } } } else if (selectorType.HasFlag(SelectorType.Elements)) { selectorType &= ~SelectorType.Elements; HashSet<IDomObject> source = new HashSet<IDomObject>(selectionSource); interimResult = new HashSet<IDomObject>(); foreach (IDomObject obj in selectionSource) { key = DomData.indexSeparator + obj.Path; HashSet<IDomObject> srcKeys = new HashSet<IDomObject>(document.QueryIndex(key)); foreach (IDomObject match in selector.SelectElements) { if (srcKeys.Contains(match)) { ((HashSet<IDomObject>)interimResult).Add(match); } } } } // TODO - GetMatch should work if passed with no selectors (returning nothing), now it returns everything // 12/10/11 - this todo is not verified, much has changed since it was written. TODO confirm this and // fix if needed. If having the conversation with self again, remove comments and forget it. This is // an example of why comments can do more harm than good. if ((selectorType & ~(SelectorType.SubSelectorNot | SelectorType.SubSelectorHas)) != 0) { IEnumerable<IDomObject> finalSelectWithin = interimResult ?? (combinatorType == CombinatorType.Chained ? lastResult : null) ?? selectionSource ?? document.ChildElements; // if there are no temporary results (b/c there was no indexed selector) then use the whole set interimResult = GetMatches(finalSelectWithin, selector); } // Deal with subselectors: has() and not() test for the presence of a selector within the children of // an element. This is essentially similar to the manual selection above. if (selectorType.HasFlag(SelectorType.SubSelectorHas) || selectorType.HasFlag(SelectorType.SubSelectorNot)) { bool isHasSelector = selectorType.HasFlag(SelectorType.SubSelectorHas); IEnumerable<IDomObject> subSelectWithin = interimResult ?? (combinatorType == CombinatorType.Chained ? lastResult : null) ?? selectionSource; // subselects are a filter. start a new interim result. HashSet<IDomObject> filteredResults = new HashSet<IDomObject>(); foreach (IDomObject obj in subSelectWithin) { bool match = true; foreach (var sub in selector.SubSelectors) { List<IDomObject> listOfOne = new List<IDomObject>(); listOfOne.Add(obj); bool has = !sub.Select(document, listOfOne).IsNullOrEmpty(); match &= isHasSelector == has; } if (match) { filteredResults.Add(obj); } } interimResult = filteredResults; } tempResult = new HashSet<IDomObject>(); if (lastResult != null) { tempResult.AddRange(lastResult); } if (interimResult != null) { tempResult.AddRange(interimResult); } lastResult = tempResult; } if (lastResult != null) { output.AddRange(lastResult); } if (output.IsNullOrEmpty()) { yield break; } else { // Selectors always return in DOM order. Selections may end up in a different order but // we always sort here. foreach (IDomObject item in output.OrderBy(item => item.Path, StringComparer.Ordinal)) { yield return item; } } ActiveSelectors.Clear(); }
public HtmlElementFactory(IDomDocument document) { Document = document; SetHtml(document.DocumentIndex.SourceHtml); IsBound = true; }
public DomElementFactory(IDomDocument document) { Document = document; }
/// <summary> /// Test if a single element matches this selector. /// </summary> /// /// <param name="document"> /// The document context /// </param> /// <param name="element"> /// The element to test /// </param> /// /// <returns> /// true if it succeeds, false if it fails. /// </returns> public bool Matches(IDomDocument document, IDomObject element) { return(ToFilterSelector().Select(document, element).Any()); }
public SelectorEngine(IDomDocument document, Selector selector) { Document = document; Selector = selector; }
public IEnumerable <IDomObject> Select(IDomDocument document, IEnumerable <IDomObject> context) { return(Engine.Select(document, context)); }
public WrongDocumentException(XmlNode nodeToAdd, IDomDocument targetDocument) : base("Cannot add attribute '" + nodeToAdd + "' to document '" + targetDocument + "' not created by document.") { }
public IEnumerable <IDomObject> Select(IDomDocument document) { return(Select(document, (IEnumerable <IDomObject>)null)); }
public IEnumerable <IDomObject> Select(IDomDocument document, IDomObject context) { return(Select(document, Objects.Enumerate(context))); }
/// <summary> /// In the future I will update the parser to do this directly, since this requires binding to a Document to work. /// </summary> public static void ReorganizeStrandedTextNodes(IDomDocument document) { if (document.DocTypeNode == null) { var docType = new DomDocumentType(DocType.HTML5); document.ChildNodes.Insert(0, docType); } // ignore everything before <html> except text; if found, start adding to <body> // if there's anything before <doctype> then it gets trashed IDomElement html = (IDomElement)document.GetElementsByTagName("html").FirstOrDefault(); if (html != null && document.GetElementsByTagName("head").FirstOrDefault() == null) { html.ChildNodes.Insert(0, document.CreateElement("head")); } IDomElement body = (IDomElement)document.GetElementsByTagName("body").FirstOrDefault(); if (body != null) { bool textYet = false; bool anythingYet = false; int bodyIndex = 0; int index = 0; // there should only be DocType & HTML. while (index < document.ChildNodes.Count) { IDomObject obj = document.ChildNodes[index]; switch (obj.NodeType) { case NodeType.DOCUMENT_TYPE_NODE: if (!anythingYet) { index++; } else { document.ChildNodes.RemoveAt(index); } break; case NodeType.ELEMENT_NODE: if (obj.NodeName == "HTML") { bodyIndex = body.ChildNodes.Length; index++; } else { if (textYet) { body.ChildNodes.Insert(bodyIndex++, obj); } else { index++; } continue; } break; case NodeType.TEXT_NODE: if (!textYet) { // if a node is only whitespace and there has not yet been a non-whitespace text node, // then ignore it. var scanner = StringScanner.Scanner.Create(obj.NodeValue); scanner.SkipWhitespace(); if (scanner.Finished) { document.ChildNodes.RemoveAt(index); continue; } else { textYet = true; } } body.ChildNodes.Insert(bodyIndex++, obj); break; default: body.ChildNodes.Insert(bodyIndex++, obj); break; } } } }
protected internal override IModelInstance CreateModelInstance(IDomDocument document) { return(new BpmnModelInstanceImpl((ModelImpl)Bpmn.Instance.BpmnModel, Bpmn.Instance.BpmnModelBuilder, document)); }
/// <summary> /// Updates the cached Document and property flags. /// </summary> /// /// <param name="document"> /// A reference to the owning document. This is also the topmost node in the tree. /// </param> protected void UpdateDocumentFlags(IDomDocument document) { _Document = document; SetDocFlags(); // I think we can get away without resetting children. When removing something from a document, // you are exclusively going to be adding it to something else. We only need to update the parents // during the add operation. if (HasChildren && _Document != null) { foreach (var item in ChildNodes.Cast<DomObject>()) { item.UpdateDocumentFlags(_Document); } } }
protected internal abstract IModelInstance CreateModelInstance(IDomDocument document);