Пример #1
0
        /// <summary>
        /// Clones any XObject into another one.
        /// </summary>
        /// <param name="this">This XObject to clone.</param>
        /// <param name="setLineColumnInfo">False to not propagate any associated <see cref="IXmlLineInfo"/> to the cloned object.</param>
        /// <returns>A clone of this object.</returns>
        public static T Clone <T>(this T @this, bool setLineColumnInfo = true) where T : XObject
        {
            XObject o = null;

            switch (@this)
            {
            case null: return(null);

            case XAttribute a: o = new XAttribute(a); break;

            case XElement e: o = new XElement(e.Name, e.Attributes().Select(a => a.Clone()), e.Nodes().Select(n => n.Clone())); break;

            case XComment c: o = new XComment(c); break;

            case XCData d: o = new XCData(d); break;

            case XText t: o = new XText(t); break;

            case XProcessingInstruction p: o = new XProcessingInstruction(p); break;

            case XDocument d: o = new XDocument(new XDeclaration(d.Declaration), d.Nodes().Select(n => n.Clone())); break;

            case XDocumentType t: o = new XDocumentType(t); break;

            default: throw new NotSupportedException(@this.GetType().AssemblyQualifiedName);
            }
            return(setLineColumnInfo ? (T)o.SetLineColumnInfo(@this) : (T)o);
        }
Пример #2
0
        public void CreateTextSimple()
        {
            Assert.Throws<ArgumentNullException>(() => new XCData((string)null));

            XCData c = new XCData("foo");
            Assert.Equal("foo", c.Value);
            Assert.Null(c.Parent);
        }
Пример #3
0
        public static XElement AddCDataNode(this XContainer parentNode, string nodeName, string value)
        {
            XElement xElement = new XElement(nodeName);
            XCData   content  = new XCData(XmlExtensions.ReplaceInvalidChar(value));

            xElement.Add(content);
            parentNode.Add(xElement);
            return(xElement);
        }
Пример #4
0
        public static XElement AddCDataNode(this XContainer parentNode, string nodeName, string value)
        {
            XElement node      = new XElement(nodeName);
            XCData   cDataNode = new XCData(ReplaceInvalidChar(value));

            node.Add(cDataNode);
            parentNode.Add(node);
            return(node);
        }
Пример #5
0
        public void TextValue()
        {
            XCData c = new XCData("xxx");
            Assert.Equal("xxx", c.Value);

            // Null value not allowed.
            Assert.Throws<ArgumentNullException>(() => c.Value = null);

            // Try setting a value.
            c.Value = "abcd";
            Assert.Equal("abcd", c.Value);
        }
Пример #6
0
        private static async Task <XNode> ReadFromAsyncInternal(XmlReader reader, CancellationToken cancellationToken)
        {
            if (reader.ReadState != ReadState.Interactive)
            {
                throw new InvalidOperationException(SR.InvalidOperation_ExpectedInteractive);
            }

            XNode ret;

            switch (reader.NodeType)
            {
            case XmlNodeType.Text:
            case XmlNodeType.SignificantWhitespace:
            case XmlNodeType.Whitespace:
                ret = new XText(reader.Value);
                break;

            case XmlNodeType.CDATA:
                ret = new XCData(reader.Value);
                break;

            case XmlNodeType.Comment:
                ret = new XComment(reader.Value);
                break;

            case XmlNodeType.DocumentType:
                var name           = reader.Name;
                var publicId       = reader.GetAttribute("PUBLIC");
                var systemId       = reader.GetAttribute("SYSTEM");
                var internalSubset = reader.Value;

                ret = new XDocumentType(name, publicId, systemId, internalSubset);
                break;

            case XmlNodeType.Element:
                return(await XElement.CreateAsync(reader, cancellationToken).ConfigureAwait(false));

            case XmlNodeType.ProcessingInstruction:
                var target = reader.Name;
                var data   = reader.Value;

                ret = new XProcessingInstruction(target, data);
                break;

            default:
                throw new InvalidOperationException(SR.Format(SR.InvalidOperation_UnexpectedNodeType, reader.NodeType));
            }

            cancellationToken.ThrowIfCancellationRequested();
            await reader.ReadAsync().ConfigureAwait(false);

            return(ret);
        }
Пример #7
0
        public void TextEquals()
        {
            XCData c1 = new XCData("xxx");
            XCData c2 = new XCData("xxx");
            XCData c3 = new XCData("yyy");

            Assert.False(c1.Equals(null));
            Assert.False(c1.Equals("foo"));
            Assert.True(c1.Equals(c1));
            Assert.False(c1.Equals(c2));
            Assert.False(c1.Equals(c3));
        }
Пример #8
0
        public static XElement ColumnNode(string name, string comment)
        {
            var columnXe = new XElement(Globals.HbmXmlNames.COLUMN,
                new XAttribute(Globals.HbmXmlNames.NAME, String.Format("[{0}]", name)));
            if (string.IsNullOrWhiteSpace(comment))
                return columnXe;

            var commentXe = new XElement(Globals.HbmXmlNames.COMMENT);
            var commentCdata = new XCData(comment);
            commentXe.Add(commentCdata);
            columnXe.Add(commentXe);
            return columnXe;
        }
Пример #9
0
        public void DeepEquals()
        {
            XCData c1 = new XCData("xxx");
            XCData c2 = new XCData("xxx");
            XCData c3 = new XCData("yyy");

            Assert.False(XNode.DeepEquals(c1, (XText)null));
            Assert.True(XNode.DeepEquals(c1, c1));
            Assert.True(XNode.DeepEquals(c1, c2));
            Assert.False(XNode.DeepEquals(c1, c3));

            Assert.Equal(XNode.EqualityComparer.GetHashCode(c1), XNode.EqualityComparer.GetHashCode(c2));
        }
Пример #10
0
                /// <summary>
                /// Tests the XCData constructor that takes a value.
                /// </summary>
                /// <param name="contextValue"></param>
                /// <returns></returns>
                //[Variation(Desc = "CreateTextSimple")]
                public void CreateTextSimple()
                {
                    try
                    {
                        new XCData((string)null);
                        Validate.ExpectedThrow(typeof(ArgumentNullException));
                    }
                    catch (Exception ex)
                    {
                        Validate.Catch(ex, typeof(ArgumentNullException));
                    }

                    XCData c = new XCData("foo");
                    Validate.IsEqual(c.Value, "foo");
                    Validate.IsNull(c.Parent);
                }
Пример #11
0
        internal static XNode ReadFrom(XmlReader r, LoadOptions options)
        {
            switch (r.NodeType)
            {
            case XmlNodeType.Element:
                return(XElement.LoadCore(r, options));

            case XmlNodeType.Whitespace:
            case XmlNodeType.SignificantWhitespace:
            case XmlNodeType.Text:
                XText t = new XText(r.Value);
                t.FillLineInfoAndBaseUri(r, options);
                r.Read();
                return(t);

            case XmlNodeType.CDATA:
                XCData c = new XCData(r.Value);
                c.FillLineInfoAndBaseUri(r, options);
                r.Read();
                return(c);

            case XmlNodeType.ProcessingInstruction:
                XPI pi = new XPI(r.Name, r.Value);
                pi.FillLineInfoAndBaseUri(r, options);
                r.Read();
                return(pi);

            case XmlNodeType.Comment:
                XComment cm = new XComment(r.Value);
                cm.FillLineInfoAndBaseUri(r, options);
                r.Read();
                return(cm);

            case XmlNodeType.DocumentType:
                XDocumentType d = new XDocumentType(r.Name,
                                                    r.GetAttribute("PUBLIC"),
                                                    r.GetAttribute("SYSTEM"),
                                                    r.Value);
                d.FillLineInfoAndBaseUri(r, options);
                r.Read();
                return(d);

            default:
                throw new InvalidOperationException(String.Format("Node type {0} is not supported", r.NodeType));
            }
        }
Пример #12
0
                /// <summary>
                /// Validate behavior of XElement creation with copy constructor.
                /// </summary>
                /// <returns>true if pass, false if fail</returns>
                //[Variation(Desc = "CreateElementCopy")]
                public void CreateElementCopy()
                {
                    // With attributes
                    XElement level2Element = new XElement("Level2", "TextValue");
                    XAttribute attribute = new XAttribute("Attribute", "AttributeValue");
                    XCData cdata = new XCData("abcdefgh");
                    string someValue = "text";

                    XElement element = new XElement("Level1", level2Element, cdata, someValue, attribute);

                    XElement elementCopy = new XElement(element);

                    Validate.ElementName(element, "Level1");

                    Validate.EnumeratorDeepEquals(
                        elementCopy.Nodes(),
                        new XNode[] { level2Element, cdata, new XText(someValue) });

                    Validate.EnumeratorAttributes(elementCopy.Attributes(), new XAttribute[1] { attribute });

                    // Without attributes
                    element = new XElement("Level1", level2Element, cdata, someValue);
                    elementCopy = new XElement(element);

                    Validate.ElementName(element, "Level1");

                    Validate.EnumeratorDeepEquals(
                        elementCopy.Nodes(),
                        new XNode[] { level2Element, cdata, new XText(someValue) });

                    Validate.EnumeratorAttributes(elementCopy.Attributes(), new XAttribute[0]);

                    // Hsh codes of equal elements shoukd be equal.
                    Validate.IsEqual(XNode.EqualityComparer.GetHashCode(element), XNode.EqualityComparer.GetHashCode(elementCopy));

                    // Null element is not allowed.
                    try
                    {
                        XElement e = new XElement((XElement)null);
                        Validate.ExpectedThrow(typeof(ArgumentNullException));
                    }
                    catch (Exception ex)
                    {
                        Validate.Catch(ex, typeof(ArgumentNullException));
                    }
                }
Пример #13
0
                /// <summary>
                /// Validate behavior of XElement creation with content supplied.
                /// </summary>
                /// <returns>true if pass, false if fail</returns>
                //[Variation(Desc = "CreateElementWithContent")]
                public void CreateElementWithContent()
                {
                    // Test the constructor that takes a name and some content.
                    XElement level2Element = new XElement("Level2", "TextValue");
                    XAttribute attribute = new XAttribute("Attribute", "AttributeValue");
                    XCData cdata = new XCData("abcdefgh");
                    string someValue = "text";

                    XElement element = new XElement("Level1", level2Element, cdata, someValue, attribute);

                    Validate.ElementName(element, "Level1");

                    Validate.EnumeratorDeepEquals(
                        element.Nodes(),
                        new XNode[] { level2Element, cdata, new XText(someValue) });

                    Validate.EnumeratorAttributes(element.Attributes(), new XAttribute[1] { attribute });
                }
Пример #14
0
 protected override XDocument GetXmlSchema()
 {
     var xdoc = base.GetXmlSchema();
     var xml = xdoc.Element("xml");
     //
     // Content
     //
     var innerData = new XCData(string.Empty);
     var outerData = new XElement("Content");
     outerData.Add(innerData);
     xml.Add(outerData);
     //
     // FuncFlag
     //
     outerData = new XElement("FuncFlag");
     xml.Add(outerData);
     return xdoc;
 }
Пример #15
0
                /// <summary>
                /// Validates the behavior of the Equals overload on XText.
                /// </summary>
                /// <returns>true if pass, false if fail</returns>
                //[Variation(Desc = "TextEquals")]
                public void TextEquals()
                {
                    XCData c1 = new XCData("xxx");
                    XCData c2 = new XCData("xxx");
                    XCData c3 = new XCData("yyy");

                    bool b1 = c1.Equals(null);
                    bool b2 = c1.Equals("foo");
                    bool b3 = c1.Equals(c1);
                    bool b4 = c1.Equals(c2);
                    bool b5 = c1.Equals(c3);

                    Validate.IsEqual(b1, false);
                    Validate.IsEqual(b2, false);
                    Validate.IsEqual(b3, true);
                    Validate.IsEqual(b4, false);
                    Validate.IsEqual(b5, false);
                }
Пример #16
0
        public void CreateElementWithContent()
        {
            // Test the constructor that takes a name and some content.
            XElement level2Element = new XElement("Level2", "TextValue");
            XAttribute attribute = new XAttribute("Attribute", "AttributeValue");
            XCData cdata = new XCData("abcdefgh");
            string someValue = "text";

            XElement element = new XElement("Level1", level2Element, cdata, someValue, attribute);

            Assert.Equal("Level1", element.Name.ToString());

            Assert.Equal(
                new XNode[] { level2Element, cdata, new XText(someValue) },
                element.Nodes(),
                XNode.EqualityComparer);

            Assert.Equal(new[] { attribute.Name }, element.Attributes().Select(x => x.Name));
            Assert.Equal(new[] { attribute.Value }, element.Attributes().Select(x => x.Value));
        }
Пример #17
0
 protected override XDocument GetXmlSchema()
 {
     var xdoc = base.GetXmlSchema();
     var xml = xdoc.Element("xml");
     //
     // Event
     //
     var innerData = new XCData(string.Empty);
     var outerData = new XElement("Event");
     outerData.Add(innerData);
     xml.Add(outerData);
     //
     // EventKey
     //
     innerData = new XCData(string.Empty);
     outerData = new XElement("EventKey");
     outerData.Add(innerData);
     xml.Add(outerData);
     return xdoc;
 }
Пример #18
0
        public void CreateElementCopy()
        {
            // With attributes
            XElement level2Element = new XElement("Level2", "TextValue");
            XAttribute attribute = new XAttribute("Attribute", "AttributeValue");
            XCData cdata = new XCData("abcdefgh");
            string someValue = "text";

            XElement element = new XElement("Level1", level2Element, cdata, someValue, attribute);

            XElement elementCopy = new XElement(element);

            Assert.Equal("Level1", element.Name.ToString());

            Assert.Equal(
                new XNode[] { level2Element, cdata, new XText(someValue) },
                elementCopy.Nodes(),
                XNode.EqualityComparer);

            Assert.Equal(new[] { attribute.Name }, element.Attributes().Select(x => x.Name));
            Assert.Equal(new[] { attribute.Value }, element.Attributes().Select(x => x.Value));

            // Without attributes
            element = new XElement("Level1", level2Element, cdata, someValue);
            elementCopy = new XElement(element);

            Assert.Equal("Level1", element.Name.ToString());

            Assert.Equal(
                new XNode[] { level2Element, cdata, new XText(someValue) },
                elementCopy.Nodes(),
                XNode.EqualityComparer);

            Assert.Empty(elementCopy.Attributes());

            // Hsh codes of equal elements shoukd be equal.
            Assert.Equal(XNode.EqualityComparer.GetHashCode(element), XNode.EqualityComparer.GetHashCode(elementCopy));

            // Null element is not allowed.
            Assert.Throws<ArgumentNullException>(() => new XElement((XElement)null));
        }
Пример #19
0
 public void XCDataChangeValue()
 {
     XCData toChange = new XCData("Original Value");
     String newValue = "New Value";
     XElement xElem = new XElement("root", toChange);
     XElement xElemOriginal = new XElement(xElem);
     using (UndoManager undo = new UndoManager(xElem))
     {
         undo.Group();
         using (EventsHelper eHelper = new EventsHelper(xElem))
         {
             using (EventsHelper dataHelper = new EventsHelper(toChange))
             {
                 toChange.Value = newValue;
                 Assert.True(toChange.Value.Equals(newValue), "Value did not change");
                 xElem.Verify();
                 dataHelper.Verify(XObjectChange.Value, toChange);
             }
             eHelper.Verify(XObjectChange.Value, toChange);
         }
         undo.Undo();
         Assert.True(XNode.DeepEquals(xElem, xElemOriginal), "Undo did not work!");
     }
 }
 /// <summary>
 /// Parse the CDATA node at the given element.
 /// </summary>
 public MarkupHtmlElement(XCData node)
     : this(node.Value)
 {
 }
Пример #21
0
            public bool ReadContentFrom(XContainer rootContainer, XmlReader r, LoadOptions o)
            {
                XNode  newNode = null;
                string baseUri = r.BaseURI;

                switch (r.NodeType)
                {
                case XmlNodeType.Element:
                {
                    XElement e = new XElement(_eCache.Get(r.NamespaceURI).GetName(r.LocalName));
                    if (_baseUri != null && _baseUri != baseUri)
                    {
                        e.SetBaseUri(baseUri);
                    }
                    if (_lineInfo != null && _lineInfo.HasLineInfo())
                    {
                        e.SetLineInfo(_lineInfo.LineNumber, _lineInfo.LinePosition);
                    }
                    if (r.MoveToFirstAttribute())
                    {
                        do
                        {
                            XAttribute a = new XAttribute(_aCache.Get(r.Prefix.Length == 0 ? string.Empty : r.NamespaceURI).GetName(r.LocalName), r.Value);
                            if (_lineInfo != null && _lineInfo.HasLineInfo())
                            {
                                a.SetLineInfo(_lineInfo.LineNumber, _lineInfo.LinePosition);
                            }
                            e.AppendAttributeSkipNotify(a);
                        } while (r.MoveToNextAttribute());
                        r.MoveToElement();
                    }
                    _currentContainer.AddNodeSkipNotify(e);
                    if (!r.IsEmptyElement)
                    {
                        _currentContainer = e;
                        if (_baseUri != null)
                        {
                            _baseUri = baseUri;
                        }
                    }
                    break;
                }

                case XmlNodeType.EndElement:
                {
                    if (_currentContainer.content == null)
                    {
                        _currentContainer.content = string.Empty;
                    }
                    // Store the line info of the end element tag.
                    // Note that since we've got EndElement the current container must be an XElement
                    XElement e = _currentContainer as XElement;
                    Debug.Assert(e != null, "EndElement received but the current container is not an element.");
                    if (e != null && _lineInfo != null && _lineInfo.HasLineInfo())
                    {
                        e.SetEndElementLineInfo(_lineInfo.LineNumber, _lineInfo.LinePosition);
                    }
                    if (_currentContainer == rootContainer)
                    {
                        return(false);
                    }
                    if (_baseUri != null && _currentContainer.HasBaseUri)
                    {
                        _baseUri = _currentContainer.parent.BaseUri;
                    }
                    _currentContainer = _currentContainer.parent;
                    break;
                }

                case XmlNodeType.Text:
                case XmlNodeType.SignificantWhitespace:
                case XmlNodeType.Whitespace:
                    if ((_baseUri != null && _baseUri != baseUri) ||
                        (_lineInfo != null && _lineInfo.HasLineInfo()))
                    {
                        newNode = new XText(r.Value);
                    }
                    else
                    {
                        _currentContainer.AddStringSkipNotify(r.Value);
                    }
                    break;

                case XmlNodeType.CDATA:
                    newNode = new XCData(r.Value);
                    break;

                case XmlNodeType.Comment:
                    newNode = new XComment(r.Value);
                    break;

                case XmlNodeType.ProcessingInstruction:
                    newNode = new XProcessingInstruction(r.Name, r.Value);
                    break;

                case XmlNodeType.DocumentType:
                    newNode = new XDocumentType(r.LocalName, r.GetAttribute("PUBLIC"), r.GetAttribute("SYSTEM"), r.Value);
                    break;

                case XmlNodeType.EntityReference:
                    if (!r.CanResolveEntity)
                    {
                        throw new InvalidOperationException(SR.InvalidOperation_UnresolvedEntityReference);
                    }
                    r.ResolveEntity();
                    break;

                case XmlNodeType.EndEntity:
                    break;

                default:
                    throw new InvalidOperationException(SR.Format(SR.InvalidOperation_UnexpectedNodeType, r.NodeType));
                }

                if (newNode != null)
                {
                    if (_baseUri != null && _baseUri != baseUri)
                    {
                        newNode.SetBaseUri(baseUri);
                    }

                    if (_lineInfo != null && _lineInfo.HasLineInfo())
                    {
                        newNode.SetLineInfo(_lineInfo.LineNumber, _lineInfo.LinePosition);
                    }

                    _currentContainer.AddNodeSkipNotify(newNode);
                    newNode = null;
                }

                return(true);
            }
Пример #22
0
 internal static DiagnosticDescription Diagnostic(
    object code,
    XCData squiggledText,
    object[] arguments = null,
    LinePosition? startLocation = null,
    Func<SyntaxNode, bool> syntaxNodePredicate = null,
    bool argumentOrderDoesNotMatter = false)
 {
     return Diagnostic(
         code,
         NormalizeDiagnosticString(squiggledText.Value),
         arguments,
         startLocation,
         syntaxNodePredicate,
         argumentOrderDoesNotMatter);
 }
Пример #23
0
        public void TextWriteTo()
        {
            XCData c = new XCData("abcd");

            // Null writer not allowed.
            Assert.Throws<ArgumentNullException>(() => c.WriteTo(null));

            // Test.
            StringBuilder stringBuilder = new StringBuilder();
            XmlWriter xmlWriter = XmlWriter.Create(stringBuilder);

            xmlWriter.WriteStartElement("x");
            c.WriteTo(xmlWriter);
            xmlWriter.WriteEndElement();

            xmlWriter.Flush();

            Assert.Equal("<?xml version=\"1.0\" encoding=\"utf-16\"?><x><![CDATA[abcd]]></x>", stringBuilder.ToString());
        }
Пример #24
0
 public override XCData Visit(XCData cdata)
 {
     return new XCData(cdata);
 }
Пример #25
0
 protected VisualBasic.VisualBasicCompilation CreateVisualBasicCompilation(
     string assemblyName,
     XCData code,
     VisualBasic.VisualBasicParseOptions parseOptions = null,
     VisualBasic.VisualBasicCompilationOptions compilationOptions = null,
     IEnumerable<MetadataReference> referencedAssemblies = null,
     IEnumerable<Compilation> referencedCompilations = null)
 {
     return CreateVisualBasicCompilation(
         assemblyName,
         code.Value,
         parseOptions,
         compilationOptions,
         referencedAssemblies,
         referencedCompilations);
 }
Пример #26
0
 protected CSharp.CSharpCompilation CreateCSharpCompilation(
     string assemblyName,
     XCData code,
     CSharp.CSharpParseOptions parseOptions = null,
     CSharp.CSharpCompilationOptions compilationOptions = null,
     IEnumerable<MetadataReference> referencedAssemblies = null,
     IEnumerable<Compilation> referencedCompilations = null)
 {
     return CreateCSharpCompilation(
         assemblyName,
         code.Value,
         parseOptions,
         compilationOptions,
         referencedAssemblies,
         referencedCompilations);
 }
        private static string SerializeToXml(TransportMessage transportMessage)
        {
            var overrides = new XmlAttributeOverrides();
            var attrs = new XmlAttributes {XmlIgnore = true};

            // Exclude non-serializable members
            overrides.Add(typeof (TransportMessage), "Body", attrs);
            overrides.Add(typeof (TransportMessage), "ReplyToAddress", attrs);
            overrides.Add(typeof (TransportMessage), "Headers", attrs);

            var sb = new StringBuilder();
            var xws = new XmlWriterSettings { Encoding = Encoding.Unicode };
            var xw = XmlWriter.Create(sb, xws);
            var xs = new XmlSerializer(typeof (TransportMessage), overrides);
            xs.Serialize(xw, transportMessage);

            var xdoc = XDocument.Parse(sb.ToString());
            var body = new XElement("Body");
            var cdata = new XCData(Encoding.UTF8.GetString(transportMessage.Body));
            body.Add(cdata);
            xdoc.SafeElement("TransportMessage").Add(body);

            sb.Clear();
            var sw = new StringWriter(sb);
            xdoc.Save(sw);

            return sb.ToString();
        }
Пример #28
0
 public XCData(XCData other)
     : base(other)
 {
 }
Пример #29
0
 internal void ReadContentFrom(XmlReader r, LoadOptions o)
 {
     if ((o & (LoadOptions.SetBaseUri | LoadOptions.SetLineInfo)) == 0)
     {
         ReadContentFrom(r);
         return;
     }
     if (r.ReadState != ReadState.Interactive) throw new InvalidOperationException(SR.InvalidOperation_ExpectedInteractive);
     XContainer c = this;
     XNode n = null;
     NamespaceCache eCache = new NamespaceCache();
     NamespaceCache aCache = new NamespaceCache();
     string baseUri = (o & LoadOptions.SetBaseUri) != 0 ? r.BaseURI : null;
     IXmlLineInfo li = (o & LoadOptions.SetLineInfo) != 0 ? r as IXmlLineInfo : null;
     do
     {
         string uri = r.BaseURI;
         switch (r.NodeType)
         {
             case XmlNodeType.Element:
                 {
                     XElement e = new XElement(eCache.Get(r.NamespaceURI).GetName(r.LocalName));
                     if (baseUri != null && baseUri != uri)
                     {
                         e.SetBaseUri(uri);
                     }
                     if (li != null && li.HasLineInfo())
                     {
                         e.SetLineInfo(li.LineNumber, li.LinePosition);
                     }
                     if (r.MoveToFirstAttribute())
                     {
                         do
                         {
                             XAttribute a = new XAttribute(aCache.Get(r.Prefix.Length == 0 ? string.Empty : r.NamespaceURI).GetName(r.LocalName), r.Value);
                             if (li != null && li.HasLineInfo())
                             {
                                 a.SetLineInfo(li.LineNumber, li.LinePosition);
                             }
                             e.AppendAttributeSkipNotify(a);
                         } while (r.MoveToNextAttribute());
                         r.MoveToElement();
                     }
                     c.AddNodeSkipNotify(e);
                     if (!r.IsEmptyElement)
                     {
                         c = e;
                         if (baseUri != null)
                         {
                             baseUri = uri;
                         }
                     }
                     break;
                 }
             case XmlNodeType.EndElement:
                 {
                     if (c.content == null)
                     {
                         c.content = string.Empty;
                     }
                     // Store the line info of the end element tag.
                     // Note that since we've got EndElement the current container must be an XElement
                     XElement e = c as XElement;
                     Debug.Assert(e != null, "EndElement received but the current container is not an element.");
                     if (e != null && li != null && li.HasLineInfo())
                     {
                         e.SetEndElementLineInfo(li.LineNumber, li.LinePosition);
                     }
                     if (c == this) return;
                     if (baseUri != null && c.HasBaseUri)
                     {
                         baseUri = c.parent.BaseUri;
                     }
                     c = c.parent;
                     break;
                 }
             case XmlNodeType.Text:
             case XmlNodeType.SignificantWhitespace:
             case XmlNodeType.Whitespace:
                 if ((baseUri != null && baseUri != uri) ||
                     (li != null && li.HasLineInfo()))
                 {
                     n = new XText(r.Value);
                 }
                 else
                 {
                     c.AddStringSkipNotify(r.Value);
                 }
                 break;
             case XmlNodeType.CDATA:
                 n = new XCData(r.Value);
                 break;
             case XmlNodeType.Comment:
                 n = new XComment(r.Value);
                 break;
             case XmlNodeType.ProcessingInstruction:
                 n = new XProcessingInstruction(r.Name, r.Value);
                 break;
             case XmlNodeType.DocumentType:
                 n = new XDocumentType(r.LocalName, r.GetAttribute("PUBLIC"), r.GetAttribute("SYSTEM"), r.Value);
                 break;
             case XmlNodeType.EntityReference:
                 if (!r.CanResolveEntity) throw new InvalidOperationException(SR.InvalidOperation_UnresolvedEntityReference);
                 r.ResolveEntity();
                 break;
             case XmlNodeType.EndEntity:
                 break;
             default:
                 throw new InvalidOperationException(SR.Format(SR.InvalidOperation_UnexpectedNodeType, r.NodeType));
         }
         if (n != null)
         {
             if (baseUri != null && baseUri != uri)
             {
                 n.SetBaseUri(uri);
             }
             if (li != null && li.HasLineInfo())
             {
                 n.SetLineInfo(li.LineNumber, li.LinePosition);
             }
             c.AddNodeSkipNotify(n);
             n = null;
         }
     } while (r.Read());
 }
Пример #30
0
		internal static XNode ReadFrom (XmlReader r, LoadOptions options)
		{
			switch (r.NodeType) {
			case XmlNodeType.Element:
				return XElement.LoadCore (r, options);
			case XmlNodeType.Whitespace:
			case XmlNodeType.SignificantWhitespace:
			case XmlNodeType.Text:
				XText t = new XText (r.Value);
				t.FillLineInfoAndBaseUri (r, options);
				r.Read ();
				return t;
			case XmlNodeType.CDATA:
				XCData c = new XCData (r.Value);
				c.FillLineInfoAndBaseUri (r, options);
				r.Read ();
				return c;
			case XmlNodeType.ProcessingInstruction:
				XPI pi = new XPI (r.Name, r.Value);
				pi.FillLineInfoAndBaseUri (r, options);
				r.Read ();
				return pi;
			case XmlNodeType.Comment:
				XComment cm = new XComment (r.Value);
				cm.FillLineInfoAndBaseUri (r, options);
				r.Read ();
				return cm;
			case XmlNodeType.DocumentType:
				XDocumentType d = new XDocumentType (r.Name,
					r.GetAttribute ("PUBLIC"),
					r.GetAttribute ("SYSTEM"),
					r.Value);
				d.FillLineInfoAndBaseUri (r, options);
				r.Read ();
				return d;
			default:
				throw new InvalidOperationException (String.Format ("Node type {0} is not supported", r.NodeType));
			}
		}
Пример #31
0
 /// <summary>
 /// Invoked for each <see cref="XCData"/>
 /// </summary>
 /// <param name="cdata"></param>
 public virtual void Visit(XCData cdata)
 {
     Contract.Requires<ArgumentNullException>(cdata != null);
 }
Пример #32
0
                /// <summary>
                /// Validates the behavior of the DeepEquals overload on XText.
                /// </summary>
                /// <returns>true if pass, false if fail</returns>
                //[Variation(Desc = "DeepEquals")]
                public void DeepEquals()
                {
                    XCData c1 = new XCData("xxx");
                    XCData c2 = new XCData("xxx");
                    XCData c3 = new XCData("yyy");

                    bool b1 = XNode.DeepEquals(c1, (XText)null);
                    bool b3 = XNode.DeepEquals(c1, c1);
                    bool b4 = XNode.DeepEquals(c1, c2);
                    bool b5 = XNode.DeepEquals(c1, c3);

                    Validate.IsEqual(b1, false);
                    Validate.IsEqual(b3, true);
                    Validate.IsEqual(b4, true);
                    Validate.IsEqual(b5, false);

                    b1 = XNode.EqualityComparer.GetHashCode(c1) == XNode.EqualityComparer.GetHashCode(c2);
                    Validate.IsEqual(b1, true);
                }
Пример #33
0
 //[Variation(Id = 9, Desc = "WriteCData with invalid surrogate pair", Priority = 1)]
 public void CData_9()
 {
     XCData xa = new XCData("\uD812");
     XElement doc = new XElement("root");
     doc.Add(xa);
     XmlWriter w = doc.CreateWriter();
     w.Dispose();
     try
     {
         doc.Save(new MemoryStream());
     }
     catch (ArgumentException)
     {
         CheckClosedState(w.WriteState);
         return;
     }
     TestLog.WriteLine("Did not throw exception");
     throw new TestException(TestResult.Failed, "");
 }
Пример #34
0
        internal void ReadContentFrom(XmlReader r, LoadOptions o)
        {
            if ((o & (LoadOptions.SetBaseUri | LoadOptions.SetLineInfo)) == 0)
            {
                ReadContentFrom(r);
                return;
            }
            if (r.ReadState != ReadState.Interactive)
            {
                throw new InvalidOperationException(SR.InvalidOperation_ExpectedInteractive);
            }
            XContainer     c       = this;
            XNode          n       = null;
            NamespaceCache eCache  = new NamespaceCache();
            NamespaceCache aCache  = new NamespaceCache();
            string         baseUri = (o & LoadOptions.SetBaseUri) != 0 ? r.BaseURI : null;
            IXmlLineInfo   li      = (o & LoadOptions.SetLineInfo) != 0 ? r as IXmlLineInfo : null;

            do
            {
                string uri = r.BaseURI;
                switch (r.NodeType)
                {
                case XmlNodeType.Element:
                {
                    XElement e = new XElement(eCache.Get(r.NamespaceURI).GetName(r.LocalName));
                    if (baseUri != null && baseUri != uri)
                    {
                        e.SetBaseUri(uri);
                    }
                    if (li != null && li.HasLineInfo())
                    {
                        e.SetLineInfo(li.LineNumber, li.LinePosition);
                    }
                    if (r.MoveToFirstAttribute())
                    {
                        do
                        {
                            XAttribute a = new XAttribute(aCache.Get(r.Prefix.Length == 0 ? string.Empty : r.NamespaceURI).GetName(r.LocalName), r.Value);
                            if (li != null && li.HasLineInfo())
                            {
                                a.SetLineInfo(li.LineNumber, li.LinePosition);
                            }
                            e.AppendAttributeSkipNotify(a);
                        } while (r.MoveToNextAttribute());
                        r.MoveToElement();
                    }
                    c.AddNodeSkipNotify(e);
                    if (!r.IsEmptyElement)
                    {
                        c = e;
                        if (baseUri != null)
                        {
                            baseUri = uri;
                        }
                    }
                    break;
                }

                case XmlNodeType.EndElement:
                {
                    if (c.content == null)
                    {
                        c.content = string.Empty;
                    }
                    // Store the line info of the end element tag.
                    // Note that since we've got EndElement the current container must be an XElement
                    XElement e = c as XElement;
                    Debug.Assert(e != null, "EndElement received but the current container is not an element.");
                    if (e != null && li != null && li.HasLineInfo())
                    {
                        e.SetEndElementLineInfo(li.LineNumber, li.LinePosition);
                    }
                    if (c == this)
                    {
                        return;
                    }
                    if (baseUri != null && c.HasBaseUri)
                    {
                        baseUri = c.parent.BaseUri;
                    }
                    c = c.parent;
                    break;
                }

                case XmlNodeType.Text:
                case XmlNodeType.SignificantWhitespace:
                case XmlNodeType.Whitespace:
                    if ((baseUri != null && baseUri != uri) ||
                        (li != null && li.HasLineInfo()))
                    {
                        n = new XText(r.Value);
                    }
                    else
                    {
                        c.AddStringSkipNotify(r.Value);
                    }
                    break;

                case XmlNodeType.CDATA:
                    n = new XCData(r.Value);
                    break;

                case XmlNodeType.Comment:
                    n = new XComment(r.Value);
                    break;

                case XmlNodeType.ProcessingInstruction:
                    n = new XProcessingInstruction(r.Name, r.Value);
                    break;

                case XmlNodeType.DocumentType:
                    n = new XDocumentType(r.LocalName, r.GetAttribute("PUBLIC"), r.GetAttribute("SYSTEM"), r.Value);
                    break;

                case XmlNodeType.EntityReference:
                    if (!r.CanResolveEntity)
                    {
                        throw new InvalidOperationException(SR.InvalidOperation_UnresolvedEntityReference);
                    }
                    r.ResolveEntity();
                    break;

                case XmlNodeType.EndEntity:
                    break;

                default:
                    throw new InvalidOperationException(SR.Format(SR.InvalidOperation_UnexpectedNodeType, r.NodeType));
                }
                if (n != null)
                {
                    if (baseUri != null && baseUri != uri)
                    {
                        n.SetBaseUri(uri);
                    }
                    if (li != null && li.HasLineInfo())
                    {
                        n.SetLineInfo(li.LineNumber, li.LinePosition);
                    }
                    c.AddNodeSkipNotify(n);
                    n = null;
                }
            } while (r.Read());
        }
Пример #35
0
        /// <summary>
        /// Gets the results as XML.
        /// </summary>
        /// <param name="results">The results.</param>
        /// <returns></returns>
        private static XPathNodeIterator GetResultsAsXml(ISearchResults results)
        {
            // create the XDocument
            XDocument doc = new XDocument();

            // check there are any search results
            if (results.TotalItemCount > 0)
            {
                // create the root element
                XElement root = new XElement("nodes");

                // iterate through the search results
                foreach (SearchResult result in results)
                {
                    // create a new <node> element
                    XElement node = new XElement("node");

                    // create the @id attribute
                    XAttribute nodeId = new XAttribute("id", result.Id);

                    // create the @score attribute
                    XAttribute nodeScore = new XAttribute("score", result.Score);

                    // add the content
                    node.Add(nodeId, nodeScore);

                    foreach (KeyValuePair<String, String> field in result.Fields)
                    {
                        // create a new <data> element
                        XElement data = new XElement("data");

                        // create the @alias attribute
                        XAttribute alias = new XAttribute("alias", field.Key);

                        // assign the value to a CDATA section
                        XCData value = new XCData(field.Value);

                        // append the content
                        data.Add(alias, value);

                        // append the <data> element
                        node.Add(data);
                    }

                    // add the node
                    root.Add(node);
                }

                // add the root node
                doc.Add(root);
            }
            else
            {
                doc.Add(new XElement("error", "There were no search results."));
            }

            return doc.CreateNavigator().Select("/");
        }
Пример #36
0
                /// <summary>
                /// Validates the behavior of the Value property on XText.
                /// </summary>
                /// <returns>true if pass, false if fail</returns>
                //[Variation(Desc = "TextValue")]
                public void TextValue()
                {
                    XCData c = new XCData("xxx");
                    Validate.IsEqual(c.Value, "xxx");

                    // Null value not allowed.
                    try
                    {
                        c.Value = null;
                        Validate.ExpectedThrow(typeof(ArgumentNullException));
                    }
                    catch (Exception ex)
                    {
                        Validate.Catch(ex, typeof(ArgumentNullException));
                    }

                    // Try setting a value.
                    c.Value = "abcd";
                    Validate.IsEqual(c.Value, "abcd");
                }
Пример #37
0
                /// <summary>
                /// Tests the WriteTo method on XTest.
                /// </summary>
                /// <param name="contextValue"></param>
                /// <returns></returns>
                //[Variation(Desc = "TextWriteTo")]
                public void TextWriteTo()
                {
                    XCData c = new XCData("abcd");

                    // Null writer not allowed.
                    try
                    {
                        c.WriteTo(null);
                        Validate.ExpectedThrow(typeof(ArgumentNullException));
                    }
                    catch (Exception ex)
                    {
                        Validate.Catch(ex, typeof(ArgumentNullException));
                    }

                    // Test.
                    StringBuilder stringBuilder = new StringBuilder();
                    XmlWriter xmlWriter = XmlWriter.Create(stringBuilder);

                    xmlWriter.WriteStartElement("x");
                    c.WriteTo(xmlWriter);
                    xmlWriter.WriteEndElement();

                    xmlWriter.Flush();

                    Validate.IsEqual(
                        stringBuilder.ToString(),
                        "<?xml version=\"1.0\" encoding=\"utf-16\"?><x><![CDATA[abcd]]></x>");
                }
 public CompilationVerifier VerifyIL(
     string qualifiedMethodName,
     XCData expectedIL,
     bool realIL = false,
     string sequencePoints = null,
     [CallerFilePath]string callerPath = null,
     [CallerLineNumber]int callerLine = 0)
 {
     return VerifyILImpl(qualifiedMethodName, expectedIL.Value, realIL, sequencePoints, callerPath, callerLine, escapeQuotes: false);
 }
Пример #39
0
        internal void ReadContentFrom(XmlReader r, LoadOptions o)
        {
            if ((o & (LoadOptions.SetLineInfo | LoadOptions.SetBaseUri)) == LoadOptions.None)
            {
                this.ReadContentFrom(r);
            }
            else
            {
                if (r.ReadState != System.Xml.ReadState.Interactive)
                {
                    throw new InvalidOperationException(System.Xml.Linq.Res.GetString("InvalidOperation_ExpectedInteractive"));
                }
                XContainer     parent  = this;
                XNode          n       = null;
                NamespaceCache cache   = new NamespaceCache();
                NamespaceCache cache2  = new NamespaceCache();
                string         baseUri = ((o & LoadOptions.SetBaseUri) != LoadOptions.None) ? r.BaseURI : null;
                IXmlLineInfo   info    = ((o & LoadOptions.SetLineInfo) != LoadOptions.None) ? (r as IXmlLineInfo) : null;
                do
                {
                    string baseURI = r.BaseURI;
                    switch (r.NodeType)
                    {
                    case XmlNodeType.Element:
                    {
                        XElement element = new XElement(cache.Get(r.NamespaceURI).GetName(r.LocalName));
                        if ((baseUri != null) && (baseUri != baseURI))
                        {
                            element.SetBaseUri(baseURI);
                        }
                        if ((info != null) && info.HasLineInfo())
                        {
                            element.SetLineInfo(info.LineNumber, info.LinePosition);
                        }
                        if (r.MoveToFirstAttribute())
                        {
                            do
                            {
                                XAttribute a = new XAttribute(cache2.Get((r.Prefix.Length == 0) ? string.Empty : r.NamespaceURI).GetName(r.LocalName), r.Value);
                                if ((info != null) && info.HasLineInfo())
                                {
                                    a.SetLineInfo(info.LineNumber, info.LinePosition);
                                }
                                element.AppendAttributeSkipNotify(a);
                            }while (r.MoveToNextAttribute());
                            r.MoveToElement();
                        }
                        parent.AddNodeSkipNotify(element);
                        if (!r.IsEmptyElement)
                        {
                            parent = element;
                            if (baseUri != null)
                            {
                                baseUri = baseURI;
                            }
                        }
                        break;
                    }

                    case XmlNodeType.Text:
                    case XmlNodeType.Whitespace:
                    case XmlNodeType.SignificantWhitespace:
                        if (((baseUri == null) || (baseUri == baseURI)) && ((info == null) || !info.HasLineInfo()))
                        {
                            parent.AddStringSkipNotify(r.Value);
                        }
                        else
                        {
                            n = new XText(r.Value);
                        }
                        break;

                    case XmlNodeType.CDATA:
                        n = new XCData(r.Value);
                        break;

                    case XmlNodeType.EntityReference:
                        if (!r.CanResolveEntity)
                        {
                            throw new InvalidOperationException(System.Xml.Linq.Res.GetString("InvalidOperation_UnresolvedEntityReference"));
                        }
                        r.ResolveEntity();
                        break;

                    case XmlNodeType.ProcessingInstruction:
                        n = new XProcessingInstruction(r.Name, r.Value);
                        break;

                    case XmlNodeType.Comment:
                        n = new XComment(r.Value);
                        break;

                    case XmlNodeType.DocumentType:
                        n = new XDocumentType(r.LocalName, r.GetAttribute("PUBLIC"), r.GetAttribute("SYSTEM"), r.Value, r.DtdInfo);
                        break;

                    case XmlNodeType.EndElement:
                    {
                        if (parent.content == null)
                        {
                            parent.content = string.Empty;
                        }
                        XElement element2 = parent as XElement;
                        if (((element2 != null) && (info != null)) && info.HasLineInfo())
                        {
                            element2.SetEndElementLineInfo(info.LineNumber, info.LinePosition);
                        }
                        if (parent == this)
                        {
                            return;
                        }
                        if ((baseUri != null) && parent.HasBaseUri)
                        {
                            baseUri = parent.parent.BaseUri;
                        }
                        parent = parent.parent;
                        break;
                    }

                    case XmlNodeType.EndEntity:
                        break;

                    default:
                        throw new InvalidOperationException(System.Xml.Linq.Res.GetString("InvalidOperation_UnexpectedNodeType", new object[] { r.NodeType }));
                    }
                    if (n != null)
                    {
                        if ((baseUri != null) && (baseUri != baseURI))
                        {
                            n.SetBaseUri(baseURI);
                        }
                        if ((info != null) && info.HasLineInfo())
                        {
                            n.SetLineInfo(info.LineNumber, info.LinePosition);
                        }
                        parent.AddNodeSkipNotify(n);
                        n = null;
                    }
                }while (r.Read());
            }
        }