Example #1
1
        public void ContainerAdd()
        {
            XElement element = new XElement("foo");

            // Adding null does nothing.
            element.Add(null);
            Assert.Empty(element.Nodes());

            // Add node, attrbute, string, some other value, and an IEnumerable.
            XComment comment = new XComment("this is a comment");
            XComment comment2 = new XComment("this is a comment 2");
            XComment comment3 = new XComment("this is a comment 3");
            XAttribute attribute = new XAttribute("att", "att-value");
            string str = "this is a string";
            int other = 7;

            element.Add(comment);
            element.Add(attribute);
            element.Add(str);
            element.Add(other);
            element.Add(new XComment[] { comment2, comment3 });

            Assert.Equal(
                new XNode[] { comment, new XText(str + other), comment2, comment3 },
                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));

            element.RemoveAll();
            Assert.Empty(element.Nodes());

            // Now test params overload.
            element.Add(comment, attribute, str, other);

            Assert.Equal(new XNode[] { comment, new XText(str + other) }, 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));

            // Not allowed to add a document as a child.
            XDocument document = new XDocument();
            Assert.Throws<ArgumentException>(() => element.Add(document));
        }
        /// <inheritdoc/>
        protected override void HandleXmlElement(SyntaxNodeAnalysisContext context, DocumentationCommentTriviaSyntax documentation, XmlNodeSyntax syntax, XElement completeDocumentation, Location[] diagnosticLocations)
        {
            if (completeDocumentation != null)
            {
                // We are working with an <include> element
                if (completeDocumentation.Nodes().OfType<XElement>().Any(element => element.Name == XmlCommentHelper.SummaryXmlTag))
                {
                    return;
                }

                if (completeDocumentation.Nodes().OfType<XElement>().Any(element => element.Name == XmlCommentHelper.InheritdocXmlTag))
                {
                    // Ignore nodes with an <inheritdoc/> tag in the included XML.
                    return;
                }
            }
            else
            {
                if (syntax != null)
                {
                    return;
                }

                if (documentation?.Content.GetFirstXmlElement(XmlCommentHelper.InheritdocXmlTag) != null)
                {
                    // Ignore nodes with an <inheritdoc/> tag.
                    return;
                }
            }

            foreach (var location in diagnosticLocations)
            {
                context.ReportDiagnostic(Diagnostic.Create(Descriptor, location));
            }
        }
Example #3
0
                /// <summary>
                /// Tests the Add methods on Container.
                /// </summary>
                /// <param name="context"></param>
                /// <returns></returns>
                //[Variation(Desc = "ContainerAdd")]
                public void ContainerAdd()
                {
                    XElement element = new XElement("foo");

                    // Adding null does nothing.
                    element.Add(null);
                    Validate.Count(element.Nodes(), 0);

                    // Add node, attrbute, string, some other value, and an IEnumerable.
                    XComment comment = new XComment("this is a comment");
                    XComment comment2 = new XComment("this is a comment 2");
                    XComment comment3 = new XComment("this is a comment 3");
                    XAttribute attribute = new XAttribute("att", "att-value");
                    string str = "this is a string";
                    int other = 7;

                    element.Add(comment);
                    element.Add(attribute);
                    element.Add(str);
                    element.Add(other);
                    element.Add(new XComment[] { comment2, comment3 });

                    Validate.EnumeratorDeepEquals(
                        element.Nodes(),
                        new XNode[] { comment, new XText(str + other), comment2, comment3 });

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

                    element.RemoveAll();
                    Validate.Count(element.Nodes(), 0);

                    // Now test params overload.
                    element.Add(comment, attribute, str, other);

                    Validate.EnumeratorDeepEquals(
                        element.Nodes(),
                        new XNode[] { comment, new XText(str + other) });

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

                    // Not allowed to add a document as a child.
                    XDocument document = new XDocument();
                    try
                    {
                        element.Add(document);
                        Validate.ExpectedThrow(typeof(ArgumentException));
                    }
                    catch (Exception ex)
                    {
                        Validate.Catch(ex, typeof(ArgumentException));
                    }
                }
 private IEnumerable< XNode > _ProcessIteration(XElement element, XNode iterVal,
                                                string iterName)
 {
     XNode val = iterVal;
     IEnumerable< XNode > results = _Env.Call( () =>
                                                   {
                                                       /* Bind the iterator symbolic name to the current value */
                                                       if ( val is XContainer )
                                                           /* Nodeset value */
                                                       {
                                                           _Env.DefineNodesetSymbol(
                                                               iterName,
                                                               ( ( XContainer ) val ).
                                                                   Nodes() );
                                                       }
                                                       else /* Text value */
                                                       {
                                                           _Env.DefineTextSymbol( iterName,
                                                                                  val.
                                                                                      ToString
                                                                                      () );
                                                       }
                                                       /* Process loop body */
                                                       return _ProcessNodes( element.Nodes() );
                                                   } );
     return results;
 }
        /// <summary>
        /// Get all available tracks from the given library
        /// </summary>
        private List<iTunesTrack> InitiTunesTracks()
        {
            XElement trackDictionary = new XElement("Tracks", from track in _itunesLibraryXDocument.Descendants("plist").Elements("dict").Elements("dict").Elements("dict")
                                                              select new XElement("track",
                                                                from key in track.Descendants("key")
                                                                select new XElement(((string)key).Replace(" ", ""), (string)(XElement)key.NextNode)));

            return (trackDictionary.Nodes().Select(track => new iTunesTrack()
            {
                Id = ((XElement)track).Element("TrackID").ToInt(0),
                Album = ((XElement)track).Element("Album").ToString(string.Empty),
                Artist = ((XElement)track).Element("Artist").ToString(string.Empty),
                AlbumArtist = ((XElement)track).Element("AlbumArtist").ToString(string.Empty),
                BitRate = ((XElement)track).Element("BitRate").ToInt(0),
                Comments = ((XElement)track).Element("Comments").ToString(string.Empty),
                Composer = ((XElement)track).Element("Composer").ToString(string.Empty),
                Genre = ((XElement)track).Element("Genre").ToString(string.Empty),
                Kind = ((XElement)track).Element("Kind").ToString(string.Empty),
                //To be able to have a + signs in the track location, we need to convert it to the correct HTML code before we use the UrlDecode
                Location = WebUtility.UrlDecode(((XElement)track).Element("Location").ToString(string.Empty).Replace(Constants.URI_LOCALHOST, string.Empty).Replace("+", "%2B")).Replace('/', Path.DirectorySeparatorChar),
                Name = ((XElement)track).Element("Name").ToString(string.Empty),
                PlayCount = ((XElement)track).Element("PlayCount").ToInt(0),
                SampleRate = ((XElement)track).Element("SampleRate").ToInt(0),
                Size = ((XElement)track).Element("Size").ToInt64(0),
                //Get the track time in total seconds
                TotalTime = ((XElement)track).Element("TotalTime").ToInt64(0) / 1000,
                TrackNumber = ((XElement)track).Element("TrackNumber").ToInt(0)
            })).ToList();
        }
Example #6
0
 public static void PrintChildElement(XElement parent)
 {
     foreach (XElement item in parent.Nodes())
     {
         Console.WriteLine(item.Name);
     }
 }
 private string GetText(XElement xelement)
 {
     string str = string.Empty;
     foreach (XNode node in xelement.Nodes())
     {
         string text = string.Empty;
         if (node is XText)
         {
             text = ((XText) node).Value;
         }
         else if (node is XElement)
         {
             text = GetText((XElement) node);
         }
         if (!string.IsNullOrEmpty(text))
         {
             if (!str.EndsWith(" "))
             {
                 str = str + " ";
             }
             str = str + text;
         }
     }
     return str;
 }
 static bool IsSingleLineText(XElement e)
 {
     if (e.HasAttributes) return false;
     foreach (XNode node in e.Nodes())
         if (!(node is XText) || ((XText)node).Value.Contains("\n")) return false;
     return true;
 }
        /// <summary>
        /// Build an expando from an XElement
        /// </summary>
        /// <param name="el"></param>
        /// <returns></returns>
        public static ElasticObject ElasticFromXElement(XElement el)
        {
            var exp = new ElasticObject();

            if (!string.IsNullOrEmpty(el.Value))
                exp.InternalValue = el.Value;

            exp.InternalName = el.Name.LocalName;

            foreach (var a in el.Attributes())
                exp.CreateOrGetAttribute(a.Name.LocalName, a.Value);

            var textNode= el.Nodes().FirstOrDefault();
             if (textNode is XText)
                {
                    exp.InternalContent = textNode.ToString();
                }

            foreach (var c in el.Elements())
            {

                var child = ElasticFromXElement(c);
                child.InternalParent = exp;
                exp.AddElement(child);
            }
            return exp;
        }
 private static void AssertSerializedField(XElement docNode, string value) {
     Assert.AreEqual(docNode.Nodes().Count(), 1);
     var fieldNode = docNode.Element("field");
     Assert.IsNotNull(fieldNode);
     Assert.AreEqual("one", fieldNode.Attribute("name").Value);
     Assert.AreEqual(value, fieldNode.Value);
 }
        /// <inheritdoc/>
        protected override void HandleXmlElement(SyntaxNodeAnalysisContext context, DocumentationCommentTriviaSyntax documentation, XmlNodeSyntax syntax, XElement completeDocumentation, Location[] diagnosticLocations)
        {
            if (syntax == null)
            {
                return;
            }

            if (completeDocumentation != null)
            {
                XElement summaryNode = completeDocumentation.Nodes().OfType<XElement>().FirstOrDefault(element => element.Name == XmlCommentHelper.SummaryXmlTag);
                if (summaryNode == null)
                {
                    // Handled by SA1604
                    return;
                }

                if (!XmlCommentHelper.IsConsideredEmpty(summaryNode))
                {
                    return;
                }
            }
            else
            {
                if (!XmlCommentHelper.IsConsideredEmpty(syntax))
                {
                    return;
                }
            }

            foreach (var location in diagnosticLocations)
            {
                context.ReportDiagnostic(Diagnostic.Create(Descriptor, location));
            }
        }
Example #12
0
        private void HandleChildCollections(XElement document, object parentObject)
        {
            IEnumerable<XNode> xNodes = document.Nodes();
            foreach (XElement element in xNodes)
            {
                if (element.Attribute("ObjectType") != null)
                {
                    if (element.Attribute("ObjectType").Value == "Collection")
                    {
                        string assemblyQualifiedClassNameCollection = element.Attribute("AssemblyQualifiedClassName").Value;
                        Type collectionType = Type.GetType(assemblyQualifiedClassNameCollection);
                        System.Collections.IList childObjectCollection = (System.Collections.IList)Activator.CreateInstance(collectionType);

                        IEnumerable<XNode> childNodes = element.Nodes();
                        foreach (XElement childElement in childNodes)
                        {
                            string assemblyQualifiedClassNameChild = childElement.Attribute("AssemblyQualifiedClassName").Value;
                            Type childType = Type.GetType(assemblyQualifiedClassNameChild);
                            object childObject = Activator.CreateInstance(childType);
                            YellowstonePathology.Business.Persistence.XmlPropertyWriter rootXmlPropertyWriter = new Persistence.XmlPropertyWriter(childElement, childObject);
                            rootXmlPropertyWriter.Write();
                            childObjectCollection.Add(childObject);
                        }

                        PropertyInfo collectionPropertyInfo = parentObject.GetType().GetProperty(element.Name.ToString());
                        collectionPropertyInfo.SetValue(parentObject, childObjectCollection, null);
                    }
                }
            }
        }
Example #13
0
 static void parseEntry(XElement en, StreamWriter wr) {
   foreach (var nd in en.Nodes()) {
     if (nd is XElement) wr.Write(string.Format("<{0}>", LowUtils.crlfSpaces(((XElement)nd).Value)));
     else if (nd is XText) wr.Write(LowUtils.crlfSpaces(((XText)nd).Value));
     else throw new Exception();
   }
 }
 /// <summary>
 /// Removes all namespaces from a XDocument
 /// </summary>
 /// <param name="e"></param>
 /// <returns></returns>
 /// <remarks>Borrowed from http://stackoverflow.com/a/7238007/41596</remarks>
 public static XElement RemoveAllNamespaces(XElement e)
 {
     return new XElement(e.Name.LocalName,
                         (from n in e.Nodes()
                          select ((n is XElement) ? RemoveAllNamespaces(n as XElement) : n)),
                         (e.HasAttributes) ? (from a in e.Attributes() select a) : null);
 }
        /// <summary>
        /// Parse the HTML node at the given element.
        /// </summary>
        public MarkupHtmlElement(XElement element)
        {
            XAttribute idAttribute = element.Attribute("id");
            if (idAttribute != null && IsPublicId(idAttribute.Value))
            {
                Id = idAttribute.Value;
            }

            MarkupNode childrenNode = MarkupNode.Parse(element.Nodes());
            if (childrenNode == null
                || (childrenNode is MarkupHtmlElement
                    && ((MarkupHtmlElement)childrenNode).Id == null
                    && ((MarkupHtmlElement)childrenNode).ChildNodes == null))
            {
                // This node and everything it contains is plain HTML; use it as is.
                Html = element.ToString(SaveOptions.DisableFormatting);
            }
            else
            {
                // UNDONE: Optimization: Any children which are just HTML can be merged into this node.

                // Extract only the top-level tag information. To do this, create a
                // new element that has only the name and attributes.
                XElement topElement = new XElement(element.Name,
                    element.Attributes()
                );
                Html = topElement.ToString(SaveOptions.DisableFormatting);

                // Add in the children nodes.
                ChildNodes =
                    childrenNode is MarkupElementCollection
                        ? (MarkupElementCollection)childrenNode
                        : new MarkupElementCollection(new MarkupElement[] { (MarkupElement)childrenNode });
            }
        }
 public void Collection()
 {
     XElement element = new XElement("Foo",
         new XElement("Bar",
             new XAttribute("id", "bar"),
             "Control content"),
         new XElement("p", "paragraph")
     );
     MarkupNode node = MarkupNode.Parse(element.Nodes());
     Assert.IsInstanceOf<MarkupElementCollection>(node);
     MarkupElementCollection collection = (MarkupElementCollection)node;
     Assert.IsNotNull(collection);
     Assert.AreEqual(2, collection.Count());
     List<MarkupElement> items = new List<MarkupElement>(collection);
     Assert.IsInstanceOf<MarkupControlInstance>(items[0]);
     Assert.IsInstanceOf<MarkupHtmlElement>(items[1]);
     Assert.AreEqual(
         "[\n" +
         "    {\n" +
         "        control: \"Bar\",\n" +
         "        id: \"bar\",\n" +
         "        content: \"Control content\"\n" +
         "    },\n" +
         "    \"<p>paragraph</p>\"\n" +
         "]",
         node.JavaScript());
 }
 /// <summary>
 ///  Common logic for if/ifdef/ifndef/else constructs
 /// </summary>
 /// <param name="conditionalElement"></param>
 /// <param name="condition"></param>
 /// <returns></returns>
 protected IEnumerable< XNode > _ProcessConditional(XElement conditionalElement,
                                                    bool condition)
 {
     return condition
                ? _ProcessNodes( conditionalElement.Nodes() )
                : _ProcessNextElse( conditionalElement );
 }
        internal void ParseSectionDefinitions(XElement root, Dictionary<string, SectionSchema> sectionSchemas)
        {
            foreach (var node in root.Nodes())
            {
                var element = node as XElement;
                if (element == null)
                {
                    continue;
                }

                if (element.Name.LocalName == KEYWORD_SECTIONGROUP)
                {
                    var group = SectionGroups.Add(element.Attribute(KEYWORD_SECTIONGROUP_NAME).Value);
                    group.Path = Name == string.Empty ? group.Name : string.Format("{0}/{1}", Path, @group.Name);
                    group.ParseSectionDefinitions(element, sectionSchemas);
                    continue;
                }

                if (element.Name.LocalName == KEYWORD_SECTION)
                {
                    var sectionDefinition = Sections.Add(element.Attribute(KEYWORD_SECTION_NAME).Value);
                    sectionDefinition.OverrideModeDefault = element.Attribute(KEYWORD_SECTION_OVERRIDEMODEDEFAULT).LoadString(KEYWORD_OVERRIDEMODE_ALLOW);
                    sectionDefinition.AllowLocation = element.Attribute(KEYWORD_SECTION_ALLOWLOCATION).LoadString(KEYWORD_TRUE);
                    sectionDefinition.AllowDefinition = element.Attribute(KEYWORD_SECTION_ALLOWDEFINITION).LoadString(KEYWORD_SECTION_ALLOWDEFINITION_EVERYWHERE);
                    sectionDefinition.Path = Name == string.Empty ? sectionDefinition.Name : string.Format("{0}/{1}", Path, sectionDefinition.Name);

                    SectionSchema schema;
                    sectionSchemas.TryGetValue(sectionDefinition.Path, out schema);
                    sectionDefinition.Schema = schema;
                }
            }
        }
Example #19
0
    private Expression NavigateCall(XElement node)
    {
      var nodes = node.Nodes().ToArray();
      Expression par = ExploreNode(nodes[0] as XElement);
      List<Expression> arguments = new List<Expression>();

      string name = node.Attribute("method").Value;
      string typename = node.Attribute("type").Value;

      Type tt = null;
      if (SerializationExtensions.TypeResolve != null)
        tt = SerializationExtensions.TypeResolve(typename);
      if (tt == null)
        tt = Type.GetType(typename, true);

      var mi = tt.GetMethod(name);

      //Expression call = Expression.Call(par
      for (int i = 1; i < nodes.Length; i++)
      {
        arguments.Add(ExploreNode(nodes[i] as XElement));
      }

      Expression result = null;
      if (arguments.Count > 0)
        result = Expression.Call(par, mi, arguments.ToArray());
      else
        result = Expression.Call(par, mi);

      return result;
    }
 public void OnXElement2()
 {
     int count = 0;
     _runWithEvents = (bool)Params[0];
     var e = new XElement("A", new XText(""));
     TestLog.Compare(e.Nodes().Any(), "Test failed:: e.Nodes().Any()");
     if (_runWithEvents)
     {
         _eHelper = new EventsHelper(e);
         count = e.Nodes().Count();
     }
     VerifyRemoveNodes(e);
     if (_runWithEvents)
     {
         _eHelper.Verify(XObjectChange.Remove, count);
     }
 }
Example #21
0
        private void ProcessXElement(XElement xElement, StringBuilder sb, bool performReplacements)
        {
            performReplacements = performReplacements && IsReplacementCandidate(xElement);

            AppendAsOpenTag(sb, xElement);
            ProcessNodes(xElement.Nodes(), sb, performReplacements);
            AppendAsCloseTag(sb, xElement);
        }
Example #22
0
		public XElement (XElement other)
		{
			if (other == null)
				throw new ArgumentNullException ("other");
			name = other.name;
			Add (other.Attributes ());
			Add (other.Nodes ());
		}
Example #23
0
        static void ChildNodeNavigation()
        {
            var bench = new XElement("bench",
                            new XElement("toolbox",
                                new XElement("handtool", "Hammer"),
                                new XElement("handtool", "Rasp")
                            ),
                            new XElement("toolbox",
                                new XElement("handtool", "Saw"),
                                new XElement("powertool", "Nailgun")
                            ),
                            new XComment("Be careful with the nailgun")
                        );

            foreach (XNode node in bench.Nodes())
            {
                Console.WriteLine(node.ToString(SaveOptions.DisableFormatting) + ".");
            }

            // Retrieving elements
            foreach (XElement e in bench.Elements())
            {
                Console.WriteLine(e.Name + "=" + e.Value);
            }

            foreach (var tool in bench.Elements("toolbox").Elements("handtool"))
            {
                Console.WriteLine("tool: {0} = {1}", tool.Name, tool.Value);
            }

            // query
            IEnumerable<string> query =
                from toolbox in bench.Elements()
                where toolbox.Elements().Any(tool => tool.Value == "Nailgun")
                select toolbox.Value;
            PrintQueryResult(query);

            query =
                from toolbox in bench.Elements()
                from tool in toolbox.Elements()
                where tool.Name == "handtool"
                select tool.Value;
            PrintQueryResult(query);

            // counts
            int x = bench.Elements("toolbox").Count();
            int y = bench.Elements().Where(e => e.Name == "toolbox").Count();
            Console.WriteLine("count1: {0}, count2: {1}", x, y);

            // Retrieving descendants
            Console.WriteLine(bench.Descendants("handtool").Count());

            foreach (XNode node in bench.DescendantNodes())
            {
                Console.WriteLine(node.ToString(SaveOptions.DisableFormatting));
            }
        }
        /// <summary>
        /// Reorder child nodes matching ChildNodeNames
        /// </summary>
        /// <param name="element">Element thats getting its children reordered</param>
        private void ReorderChildNodes(XElement element)
        {
            List<NodeCollection> nodeCollections = new List<NodeCollection>();

            var children = element.Nodes();

            // This indicates if last element matched ChildNodeNames
            bool inMatchingChildBlock = false;
            // This value changes each time a non matching ChildNodeName is reached ensuring that only sortable elements are reordered
            int childBlockIndex = 0;

            NodeCollection currentNodeCollection = null;

            // Run through children
            foreach (var child in children)
            {
                if (currentNodeCollection == null)
                {
                    currentNodeCollection = new NodeCollection();
                    nodeCollections.Add(currentNodeCollection);
                }

                if (child.NodeType == XmlNodeType.Element)
                {
                    XElement childElement = (XElement)child;

                    var isMatchingChild = ChildNodeNames.Any(match => match.IsMatch(childElement.Name));
                    if (isMatchingChild == false || inMatchingChildBlock == false)
                    {
                        childBlockIndex++;
                        inMatchingChildBlock = isMatchingChild;
                    }

                    if (isMatchingChild)
                    {
                        currentNodeCollection.SortAttributeValues = SortByAttributes.Select(x => x.GetValue(childElement)).ToArray();
                    }

                    currentNodeCollection.BlockIndex = childBlockIndex;
                }

                currentNodeCollection.Nodes.Add(child);

                if (child.NodeType == XmlNodeType.Element)
                    currentNodeCollection = null;
            }

            if (currentNodeCollection != null)
                currentNodeCollection.BlockIndex = childBlockIndex + 1;

            // sort node list
            nodeCollections = nodeCollections.OrderBy(x => x).ToList();

            // replace the element's nodes
            element.ReplaceNodes(nodeCollections.SelectMany(nc => nc.Nodes));
        }
Example #25
0
 public MessageHeader(XElement headerElement)
 {
     _name = headerElement.Name;
     _content = headerElement.Nodes();
     var mustUnderstandAttribute = headerElement.Attribute(Constants.Namespace + "mustUnderstand");
     if (mustUnderstandAttribute!= null)
     {
         _mustUnderstand = XmlConvert.ToBoolean(mustUnderstandAttribute.Value);                
     }
 }
Example #26
0
        private static void Write(XElement element, StreamWriter sw, int depth)
        {
            string singleindent = new string(' ', 3);
            string indent = new string(' ', depth * 3);
            int nodeCount = element.Nodes().Count();

            sw.Write("{0}<{1}", indent, element.Name);
            foreach (var attribute in element.Attributes()) { sw.Write(" {0}=\"{1}\"", attribute.Name, attribute.Value); }

            if (nodeCount > 0)
            {
                if (nodeCount == 1 && element.Nodes().First().NodeType == XmlNodeType.Text)
                {
                    sw.WriteLine(">{0}</{1}>", (element.Nodes().First() as XText).Value, element.Name);
                }
                else
                {
                    sw.WriteLine(">");

                    var cdata = (element.Nodes().FirstOrDefault(n => n.NodeType == XmlNodeType.CDATA) as XCData);
                    if (cdata != null)
                    {
                        sw.WriteLine("{0}<![CDATA[", singleindent + indent);
                        foreach (var centry in cdata.Value.Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries))
                        {
                            sw.WriteLine("{0}{1}", singleindent + singleindent + indent, centry);
                        }
                        sw.WriteLine("{0}]]>", singleindent + indent);
                    }

                    foreach (var child in element.Elements())
                    {
                        Write(child, sw, depth + 1);
                    }

                    sw.WriteLine("{0}</{1}>", indent, element.Name);
                }
            }
            else
            {
                sw.WriteLine(" />");
            }
        }
Example #27
0
 public void ExecuteXElementVariation(XNode[] content, int index)
 {
     XElement xElem = new XElement("root", content);
     XNode toRemove = xElem.Nodes().ElementAt(index);
     XElement xElemOriginal = new XElement(xElem);
     using (UndoManager undo = new UndoManager(xElem))
     {
         undo.Group();
         using (EventsHelper elemHelper = new EventsHelper(xElem))
         {
             toRemove.Remove();
             xElem.Verify();
             elemHelper.Verify(XObjectChange.Remove, toRemove);
         }
         undo.Undo();
         Assert.True(xElem.Nodes().SequenceEqual(xElemOriginal.Nodes(), XNode.EqualityComparer), "Undo did not work!");
         Assert.True(xElem.Attributes().EqualsAllAttributes(xElemOriginal.Attributes(), Helpers.MyAttributeComparer), "Undo did not work!");
     }
 }
Example #28
0
 public static XElement FindElement(XElement parent, string child)
 {
     IEnumerable childnodes = parent.Nodes();
     foreach (XElement item in childnodes)
     {
         if (item.Name.ToString().Equals(child))
             break;
     }
     return null;
 }
 private NSAttributedString IterateChildNodes(XElement element, CTStringAttributes baseAttribs)
 {
     NSMutableAttributedString mutString = new NSMutableAttributedString ("");
     foreach (var child in element.Nodes()) {
         NSAttributedString formatted = NodeToAttributedString (child, baseAttribs);
         if (formatted != null)
             mutString.Append (formatted);
     }
     return mutString;
 }
Example #30
0
        public bool Load (XElement XSchema)
            {
            SqlInsert = ProcessingInstance.GetTableDefinitionEntry (Name, "SqlInsert");
            SqlDelete = ProcessingInstance.GetTableDefinitionEntry (Name, "SqlDelete");
            SqlReadable = ProcessingInstance.GetTableDefinitionEntry (Name, "SqlReadable");

            String KeyItemName = String.Empty;
            foreach (XElement XEntityType in XSchema.Nodes ().OfType<XElement> ())
                {
                if (XEntityType.Name.LocalName != "EntityType")
                    continue;
                if (XEntityType.Attribute ("Name").Value != Name)
                    continue;
                foreach (XElement XProperty in XEntityType.Nodes ().OfType<XElement> ())
                    {
                    if (XProperty.Name.LocalName == "Key")
                        {
                        XElement XPropertyRef = XProperty.DescendantNodes ().OfType<XElement> ().First ();
                        if (XPropertyRef.Name.LocalName == "PropertyRef")
                            KeyItemName = XPropertyRef.Attribute ("Name").Value;
                        }
                    if (XProperty.Name.LocalName != "Property")
                        continue;
                    ItemDescription NewItem = new ItemDescription ();
                    NewItem.ProcessingInstance = ProcessingInstance;
                    NewItem.BackLinkTableDescription = this;
                    NewItem.Parent = this;
                    NewItem.Name = XProperty.Attribute("Name").Value;
                    if (NewItem.Name == KeyItemName)
                        NewItem.IsKey = true;
                    NewItem.Type = XProperty.Attribute ("Type").Value;
                    if (XProperty.Attribute ("Nullable") != null)
                        {
                        String Nullable = XProperty.Attribute ("Name").Value;
                        if (String.Compare( Nullable, "false", true) == 0)
                            {
                            NewItem.NullableProperty = false;
                            }
                        }
                    if (XProperty.Attribute ("MaxLength") != null)
                        {
                        String MaxLength = XProperty.Attribute ("MaxLength").Value;
                        NewItem.MaxLength = Convert.ToInt32 (MaxLength);
                        }

                    NewItem.ColumnDescription = ProcessingInstance.GetColumnDefinition (NewItem, Name, NewItem.Name, true);
					
                    ItemDictionary.Add (NewItem.Name, NewItem);

                    }
                }
            GetFillEntries ();
            return true;
            }
        public bool Equals(XNode x, XNode y)
        {
            if (x == null)
            {
                return(y == null);
            }
            else if (y == null)
            {
                return(false);
            }
            //throw new NotImplementedException ();
            if (x.NodeType != y.NodeType)
            {
                return(false);
            }
            switch (x.NodeType)
            {
            case XmlNodeType.Document:
                XDocument doc1 = (XDocument)x;
                XDocument doc2 = (XDocument)y;
                if (!Equals(doc1.Declaration, doc2.Declaration))
                {
                    return(false);
                }
                IEnumerator <XNode> id2 = doc2.Nodes().GetEnumerator();
                foreach (XNode n in doc1.Nodes())
                {
                    if (!id2.MoveNext())
                    {
                        return(false);
                    }
                    if (!Equals(n, id2.Current))
                    {
                        return(false);
                    }
                }
                return(!id2.MoveNext());

            case XmlNodeType.Element:
                XElement e1 = (XElement)x;
                XElement e2 = (XElement)y;
                if (e1.Name != e2.Name)
                {
                    return(false);
                }
                IEnumerator <XAttribute> ia2 = e2.Attributes().GetEnumerator();
                foreach (XAttribute n in e1.Attributes())
                {
                    if (!ia2.MoveNext())
                    {
                        return(false);
                    }
                    if (!Equals(n, ia2.Current))
                    {
                        return(false);
                    }
                }
                if (ia2.MoveNext())
                {
                    return(false);
                }
                IEnumerator <XNode> ie2 = e2.Nodes().GetEnumerator();
                foreach (XNode n in e1.Nodes())
                {
                    if (!ie2.MoveNext())
                    {
                        return(false);
                    }
                    if (!Equals(n, ie2.Current))
                    {
                        return(false);
                    }
                }
                return(!ie2.MoveNext());

            case XmlNodeType.Comment:
                XComment c1 = (XComment)x;
                XComment c2 = (XComment)y;
                return(c1.Value == c2.Value);

            case XmlNodeType.ProcessingInstruction:
                XPI p1 = (XPI)x;
                XPI p2 = (XPI)y;
                return(p1.Target == p2.Target && p1.Data == p2.Data);

            case XmlNodeType.DocumentType:
                XDocumentType d1 = (XDocumentType)x;
                XDocumentType d2 = (XDocumentType)y;
                return(d1.Name == d2.Name &&
                       d1.PublicId == d2.PublicId &&
                       d1.SystemId == d2.SystemId &&
                       d1.InternalSubset == d2.InternalSubset);

            case XmlNodeType.Text:
                return(((XText)x).Value == ((XText)y).Value);
            }
            throw new Exception("INTERNAL ERROR: should not happen");
        }
Example #32
0
 public XElement(XElement other)
 {
     name = other.name;
     Add(other.Attributes());
     Add(other.Nodes());
 }
Example #33
0
        /// <summary>
        /// transforms XML into IQueryable of User
        /// </summary>
        /// <param name="twitterResponse">xml with Twitter response</param>
        /// <returns>IQueryable of User</returns>
        public IList ProcessResults(System.Xml.Linq.XElement twitterResponse)
        {
            XNamespace atom       = "http://www.w3.org/2005/Atom";
            XNamespace twitter    = "http://api.twitter.com/";
            XNamespace openSearch = "http://a9.com/-/spec/opensearch/1.1/";

            var searchResult = new Search
            {
                ID             = twitterResponse.Element(atom + "id").Value,
                Title          = twitterResponse.Element(atom + "title").Value,
                TwitterWarning =
                    twitterResponse.Element(twitter + "warning") == null ?
                    string.Empty :
                    twitterResponse.Element(twitter + "warning").Value,
                Updated      = DateTime.Parse(twitterResponse.Element(atom + "updated").Value),
                ItemsPerPage =
                    twitterResponse.Element(openSearch + "itemsPerPage") == null ?
                    -1 :
                    int.Parse(twitterResponse.Element(openSearch + "itemsPerPage").Value),
                Language =
                    twitterResponse.Element(openSearch + "language") == null ?
                    string.Empty :
                    twitterResponse.Element(openSearch + "language").Value,
                Alternate =
                    twitterResponse.Elements(atom + "link")
                    .Where(elem => elem.Attribute("rel").Value == "alternate").Count() == 0 ?
                    string.Empty :
                    twitterResponse.Elements(atom + "link")
                    .Where(elem => elem.Attribute("rel").Value == "alternate")
                    .First()
                    .Attribute("href").Value,
                Self =
                    twitterResponse.Elements(atom + "link")
                    .Where(elem => elem.Attribute("rel").Value == "self").Count() == 0 ?
                    string.Empty :
                    twitterResponse.Elements(atom + "link")
                    .Where(elem => elem.Attribute("rel").Value == "self")
                    .First()
                    .Attribute("href").Value,
                Search =
                    twitterResponse.Elements(atom + "link")
                    .Where(elem => elem.Attribute("rel").Value == "search").Count() == 0 ?
                    string.Empty :
                    twitterResponse.Elements(atom + "link")
                    .Where(elem => elem.Attribute("rel").Value == "search")
                    .First()
                    .Attribute("href").Value,
                Refresh =
                    twitterResponse.Elements(atom + "link")
                    .Where(elem => elem.Attribute("rel").Value == "refresh").Count() == 0 ?
                    string.Empty :
                    twitterResponse.Elements(atom + "link")
                    .Where(elem => elem.Attribute("rel").Value == "refresh")
                    .First()
                    .Attribute("href").Value,
                Entries =
                    (from node in twitterResponse.Nodes()
                     let atomEntry = node as XElement
                                     where atomEntry != null && atomEntry.Name == atom + "entry"
                                     let author = atomEntry.Element(atom + "author")
                                                  select new AtomEntry
                {
                    ID = atomEntry.Element(atom + "id").Value,
                    Published = DateTime.Parse(atomEntry.Element(atom + "published").Value),
                    Title = atomEntry.Element(atom + "title").Value,
                    Content = atomEntry.Element(atom + "content").Value,
                    Updated = DateTime.Parse(atomEntry.Element(atom + "updated").Value),
                    Source = atomEntry.Element(twitter + "source").Value,
                    Language = atomEntry.Element(twitter + "lang").Value,
                    Alternate = atomEntry.Elements(atom + "link")
                                .Where(elem => elem.Attribute("rel").Value == "alternate")
                                .First()
                                .Attribute("href").Value,
                    Image = atomEntry.Elements(atom + "link")
                            .Where(elem => elem.Attribute("rel").Value == "image")
                            .First()
                            .Attribute("href").Value,
                    Author = new AtomAuthor
                    {
                        Name = author.Element(atom + "name").Value,
                        URI = author.Element(atom + "uri").Value
                    }
                }).ToList()
            };

            var searchList = new List <Search>
            {
                searchResult
            };

            return(searchList);
            //return searchList.AsQueryable();
        }
Example #34
0
 public XElement(XElement source)
 {
     name = source.name;
     Add(source.Attributes());
     Add(source.Nodes());
 }