本文整理匯總了C#中System.Xml.Linq.XElement.AncestorsAndSelf方法的典型用法代碼示例。如果您正苦於以下問題:C# XElement.AncestorsAndSelf方法的具體用法?C# XElement.AncestorsAndSelf怎麽用?C# XElement.AncestorsAndSelf使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類System.Xml.Linq.XElement
的用法示例。
在下文中一共展示了XElement.AncestorsAndSelf方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。
示例1: FillContent
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;
}
示例2: CreateFriendlyUrl
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";
}
示例3: GetTag
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;
}
示例4: GetPageElementsByScope
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;
}
}
}
示例5: GetPageElementBySiteDepth
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;
}
}
示例6: GetSiblingsCopyBySiteDepth
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());
}
}
}
示例7: Interpolate
/// <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);
}
示例8: ElementAncestors
/// <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]);
}
示例9: GetAnotId
//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++;
}
示例10: ParseStatusXML
// 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));
}
示例11: Apply
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 );
}
}
}
示例12: ParseCollectionElement
/// <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));
}
示例13: GetFileName
private static string GetFileName(XElement element)
{
return element.AncestorsAndSelf(SRC.Unit).First().Attribute("filename").Value;
}
示例14: ParseDirectMessageXML
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);
}
示例15: ToFormattedText
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;
}