Beispiel #1
0
 public AttributeRequiredConditionToValue(OpenXmlQualifiedName requiredAttribute, OpenXmlQualifiedName conditionAttribute, string value)
     : base(SemanticValidationLevel.Element)
 {
     _requiredAttribute  = requiredAttribute;
     _conditionAttribute = conditionAttribute;
     _value = value;
 }
Beispiel #2
0
 public AttributeAbsentConditionToValue(OpenXmlQualifiedName absentAttribute, OpenXmlQualifiedName conditionAttribute, params string[] values)
     : base(SemanticValidationLevel.Element)
 {
     _absentAttribute    = absentAttribute;
     _conditionAttribute = conditionAttribute;
     _values             = values;
 }
Beispiel #3
0
 public AttributeValueLessEqualToAnother(OpenXmlQualifiedName attribute, OpenXmlQualifiedName otherAttribute, bool canEqual)
     : base(SemanticValidationLevel.Element)
 {
     _attribute      = attribute;
     _otherAttribute = otherAttribute;
     _canEqual       = canEqual;
 }
 public UniqueAttributeValueConstraint(OpenXmlQualifiedName attribute, bool caseSensitive, OpenXmlQualifiedName?parent)
     : base(SemanticValidationLevel.Part)
 {
     _attribute = attribute;
     _parent    = parent;
     _comparer  = caseSensitive ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase;
 }
 public AttributeValueConditionToAnother(OpenXmlQualifiedName attribute, OpenXmlQualifiedName conditionAttribute, string[] values, string[] otherValues)
     : base(SemanticValidationLevel.Element)
 {
     _attribute          = attribute;
     _conditionAttribute = conditionAttribute;
     _values             = values;
     _otherValues        = otherValues;
 }
Beispiel #6
0
        public RelationshipTypeConstraint(OpenXmlQualifiedName attribute, string type)
            : base(SemanticValidationLevel.Part)
        {
            Debug.Assert(!string.IsNullOrEmpty(type));

            _attribute = attribute;
            _type      = type;
        }
 public IndexReferenceConstraint(OpenXmlQualifiedName attribute, string referencedPart, OpenXmlQualifiedName?referencedElementParent, OpenXmlQualifiedName referencedElement, string referencedElementName, int indexBase)
     : base(SemanticValidationLevel.Package)
 {
     _attribute        = attribute;
     _refPartType      = referencedPart;
     _refElement       = referencedElement;
     _refElementParent = referencedElementParent;
     _indexBase        = indexBase;
 }
Beispiel #8
0
        /// <summary>
        /// Initializes a new instance of the SchemaAttrAttribute.
        /// </summary>
        /// <param name="qname">Qualified name of item.</param>
        /// <remarks>This will be removed once the concept of id can be removed. Please use <see cref="SchemaAttrAttribute(string, string)"/></remarks>
        public SchemaAttrAttribute(string qname)
        {
            if (string.IsNullOrEmpty(qname))
            {
                throw new ArgumentNullException(nameof(qname));
            }

            _qname = qname;
        }
Beispiel #9
0
        public AttributeValueSetConstraint(OpenXmlQualifiedName attribute, bool isValid, string[] valueSet)
            : base(SemanticValidationLevel.Element)
        {
            Debug.Assert(valueSet.Length > 0);

            _attribute       = attribute;
            _isValidValueSet = isValid;
            _valueSet        = valueSet;
        }
        /// <summary>
        /// Initializes a new instance of the SchemaAttrAttribute.
        /// </summary>
        /// <param name="ns">Specifies the namespace of the schema attribute.</param>
        /// <param name="tag">Specifies the Tag name of the schema attribute.</param>
        public SchemaAttrAttribute(string ns, string tag)
        {
            if (string.IsNullOrEmpty(tag))
            {
                throw new ArgumentNullException(nameof(tag));
            }

            _qname = new OpenXmlQualifiedName(ns, tag);
        }
Beispiel #11
0
        public AttributeValueLengthConstraint(OpenXmlQualifiedName attribute, int minLength, int maxLength)
            : base(SemanticValidationLevel.Element)
        {
            Debug.Assert(minLength >= 0);
            Debug.Assert(maxLength >= 0);
            Debug.Assert(maxLength >= minLength);

            _attribute = attribute;
            _maxLength = maxLength;
            _minLength = minLength;
        }
Beispiel #12
0
        public ReferenceExistConstraint(OpenXmlQualifiedName refAttribute, string part, OpenXmlQualifiedName element, string elementName, OpenXmlQualifiedName attribute)
            : base(SemanticValidationLevel.Package)
        {
            Debug.Assert(!string.IsNullOrEmpty(part));

            _refAttribute = refAttribute;
            _partPath     = part;
            _element      = element;
            _elementName  = elementName;
            _attribute    = attribute;
        }
        public AttributeValueRangeConstraint(OpenXmlQualifiedName attribute, bool isValid, double minValue, bool minInclusive, double maxValue, bool maxInclusive)
            : base(SemanticValidationLevel.Element)
        {
            Debug.Assert(minValue <= maxValue);

            _attribute    = attribute;
            _isValidRange = isValid;
            _minValue     = minValue;
            _maxValue     = maxValue;
            _minInclusive = minInclusive;
            _maxInclusive = maxInclusive;
        }
        /// <summary>
        /// Initializes a new instance of the OpenXmlUnknownElement class using
        /// the supplied element name.
        /// </summary>
        /// <param name="name">
        /// The element name.
        /// </param>
        public OpenXmlUnknownElement(string name)
            : this()
        {
            if (name is null)
            {
                throw new ArgumentNullException(nameof(name));
            }

            var schema = OpenXmlQualifiedName.Parse(name);

            _prefix  = schema.Namespace.Prefix;
            _tagName = schema.Name;
        }
        /// <summary>
        /// Trys to create an OpenXmlElement from the specified namespace URI and local name.
        /// </summary>
        /// <param name="parent">The parent element.</param>
        /// <param name="fileFormat">The specified file format version.</param>
        /// <param name="namespaceUri">The namespace URI of the requested child element.</param>
        /// <param name="localName">The local name of the requested child element.</param>
        /// <returns>A new OpenXmlElement if the parent element can contains a child with the specified namespace and local name. Otherwise, returns null.</returns>
        internal static OpenXmlElement?TryCreateValidChild(this OpenXmlElement parent, FileFormatVersions fileFormat, string namespaceUri, string localName)
        {
            Debug.Assert(parent is OpenXmlCompositeElement);

            var newElement = parent.CreateElement(OpenXmlQualifiedName.Create(namespaceUri, string.Empty, localName));

            if (newElement is OpenXmlUnknownElement || !newElement.IsInVersion(fileFormat))
            {
                return(null);
            }

            return(newElement);
        }
Beispiel #16
0
        public AttributeValuePatternConstraint(OpenXmlQualifiedName attribute, string pattern)
            : base(SemanticValidationLevel.Element)
        {
            Debug.Assert(!string.IsNullOrEmpty(pattern));

            _attribute = attribute;

            if (!pattern.StartsWith("^", StringComparison.Ordinal) || !pattern.EndsWith("$", StringComparison.Ordinal))
            {
                pattern = string.Concat("^", pattern, "$");
            }

            _pattern = new Regex(pattern, RegexOptions.Compiled);
        }
Beispiel #17
0
 internal ElementMetadata(
     ReadOnlyArray <AttributeMetadata> attributes,
     ReadOnlyArray <IValidator> validators,
     ReadOnlyArray <IValidator> constraints,
     FileFormatVersions version,
     OpenXmlQualifiedName qname,
     CompiledParticle?particle,
     Lazy <ElementLookup> lookup)
 {
     Attributes   = attributes;
     Validators   = validators;
     Constraints  = constraints;
     Availability = version;
     QName        = qname;
     Particle     = particle;
     _children    = lookup;
 }
        protected static bool TryFindAttribute(OpenXmlElement element, OpenXmlQualifiedName attribute, out AttributeCollection.AttributeEntry result)
        {
            result = default;

            foreach (var entry in element.ParsedState.Attributes)
            {
                // Some schematron expressions don't have the right namespace, so we'll allow that if there's no exact match
                if (string.Equals(entry.Property.QName.Name, attribute.Name, StringComparison.Ordinal))
                {
                    result = entry;

                    if (entry.Property.QName.Namespace.Equals(attribute.Namespace))
                    {
                        return(true);
                    }
                }
            }

            return(!result.IsNil);
        }
 public AttributeMutualExclusive(OpenXmlQualifiedName attribute)
     : this(new[] { attribute })
 {
 }
 public                                             AttributeEntry this[in OpenXmlQualifiedName qname] => this[GetIndex(qname)];
 public AttributeMutualExclusive(OpenXmlQualifiedName attribute1, OpenXmlQualifiedName attribute2, OpenXmlQualifiedName attribute3, OpenXmlQualifiedName attribute4, OpenXmlQualifiedName attribute5, OpenXmlQualifiedName attribute6)
     : this(new[] { attribute1, attribute2, attribute3, attribute4, attribute5, attribute6 })
 {
 }
Beispiel #22
0
 public RelationshipExistConstraint(OpenXmlQualifiedName attribute)
     : base(SemanticValidationLevel.Part)
 {
     _attribute = attribute;
 }
        /// <summary>
        /// Populates the XML into a strong typed DOM tree.
        /// </summary>
        /// <param name="xmlReader">The XmlReader to read the XML content.</param>
        /// <param name="loadMode">Specifies a load mode that is either lazy or full.</param>
        private protected override void Populate(XmlReader xmlReader, OpenXmlLoadMode loadMode)
        {
            LoadAttributes(xmlReader);

            if (!xmlReader.IsEmptyElement)
            {
                xmlReader.Read(); // read this element

                while (!xmlReader.EOF)
                {
                    // O15:#3024890, OpenXmlCompositeElement ignores the Whitespace NodeType.
                    if (xmlReader.NodeType == XmlNodeType.Whitespace)
                    {
                        xmlReader.Skip();
                        continue;
                    }
                    else if (xmlReader.NodeType == XmlNodeType.EndElement)
                    {
                        Debug.Assert(string.Equals(xmlReader.LocalName, LocalName, StringComparison.Ordinal));
                        xmlReader.Skip(); // move to next node
                        break;
                    }

                    OpenXmlElement element = ElementFactory(xmlReader);

                    // set parent before Load( ) call. AlternateContentChoice need parent info on loading.
                    element.Parent = this;

                    bool isACB = element is AlternateContent;
                    if (isACB && element.OpenXmlElementContext is not null)
                    {
                        element.OpenXmlElementContext.ACBlockLevel++;
                    }

                    bool mcContextPushed = false;
                    if (!(element is OpenXmlMiscNode))
                    {
                        // push MC context based on the context of the child element to be loaded
                        mcContextPushed = PushMcContext(xmlReader);
                    }

                    //Process the element according to the MC behavior
                    var action = ElementAction.Normal;
                    if (OpenXmlElementContext is not null && OpenXmlElementContext.MCSettings.ProcessMode != DocumentFormat.OpenXml.Packaging.MarkupCompatibilityProcessMode.NoProcess)
                    {
                        action = OpenXmlElementContext.MCContext.GetElementAction(element, OpenXmlElementContext.MCSettings.TargetFileFormatVersions);
                    }

                    element.Load(xmlReader, loadMode);

                    if (mcContextPushed)
                    {
                        PopMcContext();
                    }

                    if (isACB && element.OpenXmlElementContext is not null)
                    {
                        element.OpenXmlElementContext.ACBlockLevel--;
                    }

                    switch (action)
                    {
                    case ElementAction.Normal:
                    {
                        AddANode(element);
                        break;
                    }

                    case ElementAction.Ignore:
                    {
                        element.Parent = null;
                        continue;
                    }

                    case ElementAction.ProcessContent:
                    {
                        element.Parent = null;
                        while (element.ChildElements.Count > 0)
                        {
                            if (element.FirstChild is not OpenXmlElement node)
                            {
                                break;
                            }

                            node.Remove();
                            var newnode = default(OpenXmlElement);

                            // If node is an UnknowElement, we should try to see whether the parent element can load the node as strong typed element
                            if (node is OpenXmlUnknownElement)
                            {
                                newnode = CreateElement(OpenXmlQualifiedName.Create(node.NamespaceUri, node.Prefix, node.LocalName));
                                if (!(newnode is OpenXmlUnknownElement))
                                {
                                    // The following method will load teh element in MCMode.Full
                                    // since the node is already MC-processed when loading as unknown type, full loading the outerXml is fine
                                    newnode.OuterXml = node.OuterXml;

                                    // unnecessary xmlns attribute will be added, remove it.
                                    RemoveUnnecessaryExtAttr(node, newnode);
                                }
                                else
                                {
                                    newnode = null;
                                }
                            }

                            if (newnode is not null)
                            {
                                AddANode(newnode);
                            }
                            else
                            {
                                //append the original node
                                AddANode(node);
                            }
                        }

                        break;
                    }

                    case ElementAction.ACBlock:
                    {
                        if (element is not AlternateContent acb)
                        {
                            break;
                        }

                        var effectiveNode = OpenXmlElementContext?.MCContext.GetContentFromACBlock(acb, OpenXmlElementContext.MCSettings.TargetFileFormatVersions);
                        if (effectiveNode is null)
                        {
                            break;
                        }

                        element.Parent       = null;
                        effectiveNode.Parent = null;
                        while (effectiveNode.FirstChild is not null)
                        {
                            var node = effectiveNode.FirstChild;
                            node.Remove();
                            AddANode(node);
                            node.CheckMustUnderstandAttr();
                        }

                        break;
                    }
                    }
                }
            }
            else
            {
                xmlReader.Skip();
            }

            // Set raw outer xml to empty to indicate that it passed
            RawOuterXml = string.Empty;
        }
 public AttributeCannotOmitConstraint(OpenXmlQualifiedName attribute)
     : base(SemanticValidationLevel.Element)
 {
     _attribute = attribute;
 }
Beispiel #25
0
        /// <summary>
        /// Load the DOM tree from the Open XML part.
        /// </summary>
        /// <param name="openXmlPart">The part this root element to be loaded from.</param>
        /// <param name="partStream">The stream of the part.</param>
        /// <returns>
        /// Returns true when the part stream is loaded successfully into this root element.
        /// Returns false when the part stream does not contain any xml element.
        /// </returns>
        /// <exception cref="InvalidDataException">Thrown when the part stream contains an incorrect root element.</exception>
        internal bool LoadFromPart(OpenXmlPart openXmlPart, Stream partStream)
        {
            if (partStream.Length < 4)
            {
                // The XmlReader.Read() method requires at least four bytes from the data stream in order to begin parsing.
                return(false);
            }

            var context = RootElementContext;

            // set MaxCharactersInDocument to limit the part size on loading DOM.
            context.XmlReaderSettings.MaxCharactersInDocument = openXmlPart.MaxCharactersInPart;

#if FEATURE_XML_PROHIBIT_DTD
            context.XmlReaderSettings.ProhibitDtd = true;                     // set true explicitly for security fix
#else
            context.XmlReaderSettings.DtdProcessing = DtdProcessing.Prohibit; // set to prohibit explicitly for security fix
#endif

            using (var xmlReader = XmlConvertingReaderFactory.Create(partStream, context.XmlReaderSettings, openXmlPart.OpenXmlPackage.StrictRelationshipFound))
            {
                context.MCSettings = openXmlPart.MCSettings;

                xmlReader.Read();

                if (xmlReader.NodeType == XmlNodeType.XmlDeclaration)
                {
                    var standaloneAttribute = xmlReader.GetAttribute("standalone");
                    if (standaloneAttribute is not null)
                    {
                        _standaloneDeclaration = standaloneAttribute.Equals("yes", StringComparison.OrdinalIgnoreCase);
                    }
                }

                if (!xmlReader.EOF)
                {
                    xmlReader.MoveToContent();
                }

                if (xmlReader.EOF ||
                    xmlReader.NodeType != XmlNodeType.Element ||
                    !xmlReader.IsStartElement())
                {
                    //the stream does NOT contains any xml element.
                    return(false);
                }

                var qname = new OpenXmlQualifiedName(xmlReader.NamespaceURI, xmlReader.LocalName);
                if (!qname.Namespace.IsKnown || !QName.Equals(qname))
                {
                    var elementQName = new XmlQualifiedName(xmlReader.LocalName, xmlReader.NamespaceURI).ToString();
                    var msg          = SR.Format(ExceptionMessages.Fmt_PartRootIsInvalid, elementQName, XmlQualifiedName.ToString());

                    throw new InvalidDataException(msg);
                }

                // remove all children and clear all attributes
                OuterXml = string.Empty;
                var mcContextPushed = PushMcContext(xmlReader);
                Load(xmlReader, context.LoadMode);
                if (mcContextPushed)
                {
                    PopMcContext();
                }
            }

            return(true);
        }
 public AttributeMutualExclusive(OpenXmlQualifiedName attribute1, OpenXmlQualifiedName attribute2, OpenXmlQualifiedName attribute3)
     : this(new[] { attribute1, attribute2, attribute3 })
 {
 }