public ProcessResult FillContent(XElement contentControl, IEnumerable<IContentItem> items) { var processResult = new ProcessResult(); var handled = false; foreach (var contentItem in items) { var itemProcessResult = FillContent(contentControl, contentItem); if (!itemProcessResult.Handled) continue; handled = true; if (!itemProcessResult.Success) processResult.Errors.AddRange(itemProcessResult.Errors); } if (!handled) return ProcessResult.NotHandledResult; if (processResult.Success && _isNeedToRemoveContentControls) { // Remove the content control for the table and replace it with its contents. foreach (var xElement in contentControl.AncestorsAndSelf(W.sdt)) { xElement.RemoveContentControl(); } } return processResult; }
private static string CreateFriendlyUrl(XElement topic) { var result = new StringBuilder(); var topicsRelevantForUrlGeneration = topic.AncestorsAndSelf("HelpTOCNode"); foreach (var element in topicsRelevantForUrlGeneration.Reverse()) { result.AppendFormat(" {0}", element.Attribute("Title").Value); } return result.ToString().Trim().Replace(" ", "-") + ".html"; }
public static List<string> GetTag(XElement element) { var result = element.Ancestors("compilationUnit") .Elements("packageDeclaration") .Select(e => e.ElementAt(1).Value) .ToList(); result.AddRange( element.AncestorsAndSelf() .Where( e => e.Name.LocalName == "normalClassDeclaration" || e.Name.LocalName == "methodDeclaration") // ReSharper disable PossibleNullReferenceException .Select(e => e.Element("IDENTIFIER").Value) // ReSharper restore PossibleNullReferenceException .Reverse()); return result; }
internal static IEnumerable<XElement> GetPageElementsByScope(SitemapScope associationScope, XElement currentPageElement) { IEnumerable<XElement> scopeElements = null; XElement matchPage; switch (associationScope) { case SitemapScope.Parent: if (currentPageElement.Parent != null && currentPageElement.Parent.Name == PageElementName) { yield return currentPageElement.Parent; } break; case SitemapScope.Descendants: scopeElements = currentPageElement.Descendants(PageElementName); break; case SitemapScope.DescendantsAndCurrent: scopeElements = currentPageElement.DescendantsAndSelf(PageElementName); break; case SitemapScope.Children: scopeElements = currentPageElement.Elements(PageElementName); break; case SitemapScope.Siblings: scopeElements = currentPageElement.Parent.Elements(PageElementName); break; case SitemapScope.Ancestors: scopeElements = currentPageElement.Ancestors(PageElementName); break; case SitemapScope.AncestorsAndCurrent: scopeElements = currentPageElement.AncestorsAndSelf(PageElementName); break; case SitemapScope.Level1: scopeElements = GetPageElementBySiteDepth(currentPageElement, 1); break; case SitemapScope.Level2: scopeElements = GetPageElementBySiteDepth(currentPageElement, 2); break; case SitemapScope.Level3: scopeElements = GetPageElementBySiteDepth(currentPageElement, 3); break; case SitemapScope.Level4: scopeElements = GetPageElementBySiteDepth(currentPageElement, 4); break; case SitemapScope.Level1AndDescendants: scopeElements = GetPageElementBySiteDepth(currentPageElement, 1).DescendantsAndSelf(); break; case SitemapScope.Level2AndDescendants: scopeElements = GetPageElementBySiteDepth(currentPageElement, 2).DescendantsAndSelf(); break; case SitemapScope.Level3AndDescendants: scopeElements = GetPageElementBySiteDepth(currentPageElement, 3).DescendantsAndSelf(); break; case SitemapScope.Level4AndDescendants: scopeElements = GetPageElementBySiteDepth(currentPageElement, 4).DescendantsAndSelf(); break; case SitemapScope.Level1AndSiblings: matchPage = GetPageElementBySiteDepth(currentPageElement, 1).FirstOrDefault(); if (matchPage != null && matchPage.Parent != null) { scopeElements = matchPage.Parent.Elements(PageElementName); } break; case SitemapScope.Level2AndSiblings: matchPage = GetPageElementBySiteDepth(currentPageElement, 1).FirstOrDefault(); if (matchPage != null) { scopeElements = matchPage.Elements(PageElementName); } break; case SitemapScope.Level3AndSiblings: matchPage = GetPageElementBySiteDepth(currentPageElement, 2).FirstOrDefault(); if (matchPage != null) { scopeElements = matchPage.Elements(PageElementName); } break; case SitemapScope.Level4AndSiblings: matchPage = GetPageElementBySiteDepth(currentPageElement, 3).FirstOrDefault(); if (matchPage != null) { scopeElements = matchPage.Elements(PageElementName); } break; default: throw new NotImplementedException("Unhandled SitemapScope type: " + associationScope); } if (scopeElements != null) { foreach (XElement scopeElement in scopeElements) { yield return scopeElement; } } }
private static IEnumerable<XElement> GetPageElementBySiteDepth(XElement associatedPageElement, int siteDepth) { XElement match = associatedPageElement.AncestorsAndSelf(PageElementName).Reverse().Take(siteDepth).LastOrDefault(); if (match != null && match.Attribute("Depth").Value == siteDepth.ToString()) { yield return match; } }
private static IEnumerable<XElement> GetSiblingsCopyBySiteDepth(XElement associatedPageElement, int siteDepth) { int currentPageDepth = Int32.Parse(associatedPageElement.Attribute(AttributeNames.Depth).Value); IEnumerable<XElement> elementsToCopy = null; if (siteDepth == 1) { elementsToCopy = associatedPageElement.AncestorsAndSelf(PageElementName).Where(f => f.Attribute(AttributeNames.Depth).Value == "1"); } else if (currentPageDepth >= siteDepth) { elementsToCopy = associatedPageElement.AncestorsAndSelf(PageElementName).Where(f => f.Attribute(AttributeNames.Depth).Value == (siteDepth - 1).ToString()).Elements(PageElementName); } else { if (currentPageDepth == siteDepth - 1) { elementsToCopy = associatedPageElement.Elements(PageElementName); } } if (elementsToCopy != null) { foreach (XElement pageElement in elementsToCopy) { yield return new XElement(pageElement.Name, pageElement.Attributes()); } } }
/// <summary> /// Интерполирует исходный элемет в целевой /// </summary> /// <param name="source"></param> /// <param name="baseelement"></param> /// <returns></returns> public XElement Interpolate(XElement source, XElement baseelement) { var datasources = baseelement.AncestorsAndSelf().Reverse().ToArray(); Scope cfg = null; foreach (var element in datasources) { cfg = new Scope(cfg); foreach (var attribute in element.Attributes()) { cfg.Set(attribute.Name.LocalName, attribute.Value); } var selftext = string.Join(Environment.NewLine, element.Nodes().OfType<XText>().Select(_ => _.Value)); if (!string.IsNullOrWhiteSpace(selftext) && !cfg.ContainsOwnKey("__value")) { cfg.Set("__value", selftext); } } return Interpolate(source, cfg); }
/// <summary> /// Validate enumeration of element ancestors. /// </summary> /// <param name="contextValue"></param> /// <returns></returns> //[Variation(Desc = "ElementAncestors")] public void ElementAncestors() { XElement level3 = new XElement("Level3"); XElement level2 = new XElement("Level2", level3); XElement level1 = new XElement("Level1", level2); XElement level0 = new XElement("Level1", level1); Validate.EnumeratorDeepEquals(level3.Ancestors(), new XElement[] { level2, level1, level0 }); Validate.EnumeratorDeepEquals(level3.Ancestors("Level1"), new XElement[] { level1, level0 }); Validate.EnumeratorDeepEquals(level3.Ancestors(null), new XElement[0]); Validate.EnumeratorDeepEquals(level3.AncestorsAndSelf(), new XElement[] { level3, level2, level1, level0 }); Validate.EnumeratorDeepEquals(level3.AncestorsAndSelf("Level3"), new XElement[] { level3 }); Validate.EnumeratorDeepEquals(level3.AncestorsAndSelf(null), new XElement[0]); }
//public string Name; public static void GetAnotId(XElement el, out int id, out int count) { Anot res = GetAnot(el); if (res.Id == -1) { res.Id = 0; XElement root = el.AncestorsAndSelf().Last(); Dictionary<string, int> dictCount = root.Annotation<Dictionary<string, int>>(); if (dictCount == null) { dictCount = new Dictionary<string, int>(); root.AddAnnotation(dictCount); } string nm = el.Name.ToString(); if (!dictCount.TryGetValue(nm, out res.Id)) dictCount.Add(nm, res.Id); else res.Id++; dictCount[nm] = res.Id; } id = res.Id; count = res.Count; res.Count++; }
// Internal Methods that handle the actual parsing of the XML // using XML to LINQ private static StatusMessage ParseStatusXML(XElement element) { StatusMessage Output = null; var statusQuery = from statusElement in element.AncestorsAndSelf() select new { id = statusElement.Element("id").Value, timestamp = statusElement.Element("created_at").Value, messageText = statusElement.Element("text").Value, source = statusElement.Element("source").Value, truncated = statusElement.Element("truncated").Value, inReplyStatusId = statusElement.Element("in_reply_to_status_id").Value, inReplyUserId = statusElement.Element("in_reply_to_user_id").Value }; var status = statusQuery.FirstOrDefault(); return new StatusMessage(Convert.ToInt64(status.id), DateTime.ParseExact(status.timestamp, "ddd MMM dd HH:mm:ss zzz yyyy", CultureInfo.InvariantCulture), status.messageText, null, status.inReplyStatusId.Equals(String.Empty) ? long.MinValue : Convert.ToInt64(status.inReplyStatusId), status.inReplyUserId.Equals(String.Empty) ? long.MinValue : Convert.ToInt64(status.inReplyUserId), status.source, Convert.ToBoolean(status.truncated)); }
Apply( XElement from, XElement to, IEnumerable< ElementMatchRule > rules ) { if( from == null ) throw new ArgumentNullException( "from" ); if( to == null ) throw new ArgumentNullException( "to" ); if( rules == null ) throw new ArgumentNullException( "rules" ); XElement fromroot = from.AncestorsAndSelf().Last(); // Attributes foreach( var a in from.Attributes() ) to.SetAttributeValue( a.Name, a.Value ); foreach( XNode n in from.Nodes() ) { // Text if( n is XText ) { var t = n as XText; to.Add( new XText( t ) ); } // Elements if( n is XElement ) { var e1 = n as XElement; // Find matching element... var rule = rules .Where( r => r.AppliesTo( fromroot ).Contains( e1 ) ) .FirstOrDefault(); var e2 = rule != null ? to.Elements() .Where( e => rule.Match( e1, e ) ) .SingleOrDefault() : null; // ...otherwise create it if( e2 == null ) { e2 = new XElement( e1.Name ); to.Add( e2 ); } // Recurse Apply( e1, e2, rules ); } } }
/// <summary> /// Parses the <collection> element in a service document and initializes a dictionary of entitySet name to collection root Uri /// </summary> /// <param name="collectionElement">The collection element from the service document</param> private void ParseCollectionElement(XElement collectionElement) { string hrefAttribute = string.Empty; string collectionName = string.Empty; // <collection href="root uri of collection"> // <atom:title>name of the collection</atom:title> // </collection> ExceptionUtilities.CheckObjectNotNull(collectionElement.Element(ODataConstants.TitleElement), "Collection element did not contain a <title> element"); collectionName = collectionElement.Element(ODataConstants.TitleElement).Value; if (collectionElement.Attribute(ODataConstants.HrefAttribute) == null) { hrefAttribute = collectionName; } else { hrefAttribute = collectionElement.Attribute(ODataConstants.HrefAttribute).Value; } Uri collectionRoot = new Uri(hrefAttribute, UriKind.RelativeOrAbsolute); // if the <href> attribute on a <collection> element points to a relative uri, if (!collectionRoot.IsAbsoluteUri) { var baseAttribute = collectionElement.AncestorsAndSelf().Select(element => element.Attribute(ODataConstants.XmlBaseAttribute)).Where(baseElement => baseElement != null).FirstOrDefault(); ExceptionUtilities.Assert(baseAttribute != null, "Service document did not contain a valid base uri for the collection '{0}'", collectionName); collectionRoot = new Uri(string.Format(CultureInfo.InvariantCulture, "{0}/{1}", baseAttribute.Value.TrimEnd('/'), collectionRoot.OriginalString.TrimStart('/')), UriKind.Absolute); } this.entitySetLinks[collectionName] = collectionRoot; // <collection href="root uri of collection"> // <atom:title>name of the collection</atom:title> // <m:inline xmlns:m="http://docs.oasis-open.org/odata/ns/metadata"> // <service> // <workspace> // <collection href="root uri of collection"> // <atom:title>name of the collection</atom:title> // </collection> // </workspace> // </service> // </m:inline> // </collection> // if the service document contains any inline expanded service documents, we will parse those too. (from inlineElement in collectionElement.Elements(ODataConstants.InlineElement) from serviceElement in inlineElement.Elements(ODataConstants.ServiceElement) select serviceElement).ToList().ForEach(inlineService => this.ParseInternal(inlineService)); }
private static string GetFileName(XElement element) { return element.AncestorsAndSelf(SRC.Unit).First().Attribute("filename").Value; }
private static DirectMessage ParseDirectMessageXML(XElement element) { var dmQuery = from dm in element.AncestorsAndSelf("direct_message") select new { id = dm.Element("id").Value, timestamp = dm.Element("created_at").Value, messageText = dm.Element("text").Value }; var directMsg = dmQuery.FirstOrDefault(); return new DirectMessage(Convert.ToInt64(directMsg.id), DateTime.ParseExact(directMsg.timestamp, "ddd MMM dd HH:mm:ss zzz yyyy", CultureInfo.InvariantCulture), directMsg.messageText, null, null); }
internal static FormattedText ToFormattedText(XElement e) { // The text representation of e. var text = ToText(e); if (text == string.Empty) return null; // Save footnoteId for lookup string footnoteId = null; if (e.Name.Equals(XName.Get("footnoteReference", DocX.w.NamespaceName))) footnoteId = e.GetAttribute(XName.Get("id", DocX.w.NamespaceName)); // e is a w:t element, it must exist inside a w:r element or a w:tabs, lets climb until we find it. while (!e.Name.Equals(XName.Get("r", DocX.w.NamespaceName)) && !e.Name.Equals(XName.Get("tabs", DocX.w.NamespaceName))) e = e.Parent; // e is a w:r element, lets find the rPr element. XElement rPr = e.Element(XName.Get("rPr", DocX.w.NamespaceName)); // Find the id of the containing hyperlink, if any. var containingHyperlink = e.AncestorsAndSelf(XName.Get("hyperlink", DocX.w.NamespaceName)).FirstOrDefault(); var ft = new FormattedText { text = text, containingHyperlinkId = containingHyperlink != null ? containingHyperlink.GetAttribute(XName.Get("id", DocX.r.NamespaceName), null) : null, footnoteId = footnoteId }; // Return text with formatting. if (rPr != null) ft.formatting = Formatting.Parse(rPr); return ft; }
private static SavedSearch ParseSavedSearchXml(XElement element) { var savedSearchQuery = from e in element.AncestorsAndSelf("saved_search") select new { id = e.Element("id").Value, name = e.Element("name").Value, query = e.Element("query").Value, position = e.Element("position").Value, createdAt = e.Element("created_at").Value }; var savedSearch = savedSearchQuery.FirstOrDefault(); SavedSearch Output = new SavedSearch(Convert.ToInt64(savedSearch.id), savedSearch.name, savedSearch.query, savedSearch.position, DateTime.ParseExact(savedSearch.createdAt, "ddd MMM dd HH:mm:ss zzz yyyy", CultureInfo.InvariantCulture)); return Output; }
static void PrintPath(XElement e) { var nodes = e.AncestorsAndSelf() .Reverse(); foreach (var n in nodes) Console.Write(n.Name + (n == e ? "" : "->")); }
private static IUser ParseUserXml(XElement element) { var userQuery = from userElement in element.AncestorsAndSelf() select new { id = userElement.Element("id").Value, realName = userElement.Element("name").Value, screenName = userElement.Element("screen_name").Value, description = userElement.Element("description").Value, location = userElement.Element("location").Value, profileImageUrl = userElement.Element("profile_image_url").Value, website = userElement.Element("url").Value, protectedUpdates = userElement.Element("protected").Value, followerCount = userElement.Element("followers_count").Value, createdAt = userElement.Element("created_at").Value, favorites_count = userElement.Element("favourites_count").Value, utc_offset = userElement.Element("utc_offset").Value, time_zone = userElement.Element("time_zone").Value, profile_background_image_url = userElement.Element("profile_background_image_url").Value, profile_background_tile = userElement.Element("profile_background_tile").Value, statuses_count = userElement.Element("statuses_count").Value, notifications = userElement.Element("notifications").Value, following = userElement.Element("following").Value, profile_background_color = userElement.Element("profile_background_color").Value, profile_text_color = userElement.Element("profile_text_color").Value, profile_link_color = userElement.Element("profile_link_color").Value, profile_sidebar_fill_color = userElement.Element("profile_sidebar_fill_color").Value, profile_sidebar_border_color = userElement.Element("profile_sidebar_border_color").Value }; var user = userQuery.FirstOrDefault(); long id = Convert.ToInt64(user.id); bool protectedUpdates = Convert.ToBoolean(user.protectedUpdates); long followerCount = Convert.ToInt64(user.followerCount); int favoritesCount = Convert.ToInt32(user.favorites_count); bool following = user.following.Equals(String.Empty) ? false : Convert.ToBoolean(user.following); bool notifications = user.notifications.Equals(String.Empty) ? false : Convert.ToBoolean(user.notifications); bool profileBackgroundTile = user.profile_background_tile.Equals(String.Empty) ? false : Convert.ToBoolean(user.profile_background_tile); long statuses_count = Convert.ToInt64(user.statuses_count); int utcOffset = user.utc_offset.Equals(String.Empty) ? 0 : Convert.ToInt32(user.utc_offset); return new User(id, user.realName, user.screenName, user.description, user.location, user.profileImageUrl, user.website, protectedUpdates, followerCount, DateTime.ParseExact(user.createdAt, "ddd MMM dd HH:mm:ss zzz yyyy", CultureInfo.InvariantCulture), favoritesCount, following, notifications, user.profile_background_image_url, profileBackgroundTile, user.profile_background_color, user.profile_link_color, user.profile_sidebar_fill_color, user.profile_sidebar_border_color, user.profile_text_color, statuses_count, user.time_zone, utcOffset); }
private void Keys(XElement element, CompareAction action, string component, string fileName, bool includeAllLevels = true) { var ancestors = element.AncestorsAndSelf().Select(i => i.Name.LocalName).Reverse().ToList(); var xpath = string.Concat("\\\\", string.Join("\\", ancestors)); var parsedAction = element.HasElements ? string.Format("{0} section", action.ToString()) : string.Format("{0} key", action.ToString()); Diffs.Add(new XmlDifferences { Action = parsedAction, Component = component, Config = fileName, Sprint = Sprint, XPath = xpath }); if (element.HasElements && includeAllLevels) { AllKeys(element.Elements().ToList(), action, component, fileName, includeAllLevels); } }
private static string GetCondition(XElement el) { XElement nearestconditionel = el .AncestorsAndSelf() .Where(a => a.Attribute("Condition") != null) .FirstOrDefault(); if (nearestconditionel == null) { return null; } return nearestconditionel.Attribute("Condition").Value; }
private static XElement GetPageCopyBySiteDepth(XElement associatedPageElement, int siteDepth, bool shallow) { string siteDepthStr = siteDepth.ToString(); XElement match = associatedPageElement.AncestorsAndSelf(PageElementName).SingleOrDefault(f => f.Attribute(AttributeNames.Depth).Value == siteDepthStr); if (match == null) { return null; } if (shallow) { return new XElement(match.Name, match.Attributes()); } return new XElement(match); }
public void ElementAncestors() { XElement level3 = new XElement("Level3"); XElement level2 = new XElement("Level2", level3); XElement level1 = new XElement("Level1", level2); XElement level0 = new XElement("Level1", level1); Assert.Equal(new XElement[] { level2, level1, level0 }, level3.Ancestors(), XNode.EqualityComparer); Assert.Equal(new XElement[] { level1, level0 }, level3.Ancestors("Level1"), XNode.EqualityComparer); Assert.Empty(level3.Ancestors(null)); Assert.Equal( new XElement[] { level3, level2, level1, level0 }, level3.AncestorsAndSelf(), XNode.EqualityComparer); Assert.Equal(new XElement[] { level3 }, level3.AncestorsAndSelf("Level3"), XNode.EqualityComparer); Assert.Empty(level3.AncestorsAndSelf(null)); }
private string GetRegistrationNumber(XElement sender) { if (sender == null) { return string.Empty; } var associatedProducerElement = sender.AncestorsAndSelf().FirstOrDefault(e => e.Name.LocalName == "producer"); if (associatedProducerElement == null) { return string.Empty; } var registrationNoElement = associatedProducerElement.Elements().FirstOrDefault(e => e.Name.LocalName == "registrationNo"); return registrationNoElement != null ? registrationNoElement.Value : string.Empty; }