本文整理匯總了C#中System.Xml.Linq.XElement.Ancestors方法的典型用法代碼示例。如果您正苦於以下問題:C# XElement.Ancestors方法的具體用法?C# XElement.Ancestors怎麽用?C# XElement.Ancestors使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類System.Xml.Linq.XElement
的用法示例。
在下文中一共展示了XElement.Ancestors方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。
示例1: Tag
public override List<string> Tag(XElement element) {
return element.Ancestors()
.Where(e => e.Name.LocalName == "classdef")
.Select(e => e.NthElementOrDefault(1))
.Where(e => e != null)
.Select(e => e.Value)
.ToList();
}
示例2: GetAccessModifierForMethod
/// <summary>
/// Gets the access modifiers for this method. In C++, methods are contained within
/// "specifier" blocks
/// </summary>
/// <param name="methodElement">The method typeUseElement</param>
/// <returns>The access modifier for this method; if none, it returns see
/// cref="AccessModifier.None"/></returns>
protected override AccessModifier GetAccessModifierForMethod(XElement methodElement) {
Dictionary<XName, AccessModifier> accessModifierMap = new Dictionary<XName, AccessModifier>() {
{ SRC.Public, AccessModifier.Public },
{ SRC.Private, AccessModifier.Private },
{ SRC.Protected, AccessModifier.Protected },
};
var specifiers = from container in methodElement.Ancestors()
where SpecifierContainerNames.Contains(container.Name)
select accessModifierMap[container.Name];
return (specifiers.Any() ? specifiers.First() : AccessModifier.None);
}
示例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: ExtractCategories
private static IEnumerable<string> ExtractCategories(XElement testCaseNode)
{
var categories = NUnitParsingHelper.GetCategories(testCaseNode, true);
// if this is a parameterized test, get the categories from the parent test-suite
var parameterizedTestElement = testCaseNode
.Ancestors("test-suite").ToList()
.Where(x => x.Attribute("type").Value == "ParameterizedTest")
.FirstOrDefault();
if (null != parameterizedTestElement)
{
var paramCategories = NUnitParsingHelper.GetCategories(parameterizedTestElement, false);
categories.AddRange(paramCategories);
}
return categories;
}
示例5: BuildRec
public static ElementCompileTreeNode BuildRec(XElement element)
{
int depth = element.Ancestors().Count();
var debugInfo = new XmlSourceNodeInformation(depth, element.Name.LocalName, element.Name.LocalName, element.Name.NamespaceName);
var result = new ElementCompileTreeNode(debugInfo);
foreach (var attribute in element.Attributes())
{
if (attribute.Name.LocalName == "xmlns") continue;
bool isNamespaceDeclaration = attribute.Name.Namespace == "http://www.w3.org/2000/xmlns/";
var property = new PropertyCompileTreeNode(attribute.Name.LocalName, debugInfo, isNamespaceDeclaration);
property.Value = StringResourceSystemFacade.ParseString(attribute.Value);
result.AddNamedProperty(property);
}
foreach (var node in element.Nodes())
{
if (node is XElement)
{
result.Children.Add(BuildRec(node as XElement));
continue;
}
if (node is XText)
{
string text = (node as XText).Value;
if (string.IsNullOrWhiteSpace(text))
{
continue;
}
var textProperty = new PropertyCompileTreeNode(CompilerGlobals.DefaultPropertyName, debugInfo);
textProperty.Value = StringResourceSystemFacade.ParseString(text);
result.DefaultProperties.Add(textProperty);
continue;
}
}
return result;
}
示例6: RetrieveStructElement
public static StructElement RetrieveStructElement(XElement field, List<ProgramElement> programElements)
{
IEnumerable<XElement> ownerStructs =
from el in field.Ancestors(SRC.Struct)
select el;
if (ownerStructs.Count() > 0)
{
XElement name = ownerStructs.First().Element(SRC.Name);
string ownerStructName = name.Value;
//now find the StructElement object corresponding to ownerClassName, since those should have been gen'd by now
ProgramElement ownerStruct = programElements.Find(element => element is StructElement && ((StructElement)element).Name == ownerStructName);
return ownerStruct as StructElement;
}
else
{
//field is not contained by a class
return null;
}
}
示例7: MatchesLocalVariable
private static bool MatchesLocalVariable(SrcMLDataContext db, VariableDeclaration def, XElement use)
{
if (def.IsGlobal ?? false)
return false;
if (def.DeclarationName != use.Value)
return false;
var useXPath = use.GetXPath(false);
var validScopes = from scope in db.ValidScopes
where scope.DefinitionId == def.Id
select scope;
foreach (var scope in validScopes)
{
if (useXPath.StartsWith(scope.XPath))
return true;
}
var method = (from ancestor in use.Ancestors()
where ContainerNames.MethodDefinitions.Any(mn => mn == ancestor.Name)
select ancestor).FirstOrDefault();
var classNameFromMethod = SrcMLHelper.GetClassNameForMethod(method);
if (null == classNameFromMethod)
{
return false;
}
var classDef = from scope in def.ValidScopes.OfType<TypeDefinition>()
where scope.TypeName == classNameFromMethod.Value
select scope;
if (classDef.Any())
{
return true;
}
return false;
}
示例8: DetermineRunMarks
private static void DetermineRunMarks(XElement run, XElement rPr, Dictionary<string, string> style, out XEntity runStartMark, out XEntity runEndMark)
{
runStartMark = null;
runEndMark = null;
// Only do the following for text runs.
if (run.Element(W.t) == null) return;
// Can't add directional marks if the font-family is symbol - they are visible, and display as a ?
var addDirectionalMarks = true;
if (style.ContainsKey("font-family"))
{
if (style["font-family"].ToLower() == "symbol")
addDirectionalMarks = false;
}
if (!addDirectionalMarks) return;
var isRtl = rPr.Element(W.rtl) != null;
if (isRtl)
{
runStartMark = new XEntity("#x200f"); // RLM
runEndMark = new XEntity("#x200f"); // RLM
}
else
{
var paragraph = run.Ancestors(W.p).First();
var paraIsBidi = paragraph
.Elements(W.pPr)
.Elements(W.bidi)
.Any(b => b.Attribute(W.val) == null || b.Attribute(W.val).ToBoolean() == true);
if (paraIsBidi)
{
runStartMark = new XEntity("#x200e"); // LRM
runEndMark = new XEntity("#x200e"); // LRM
}
}
}
示例9: CalcWidthOfRunInTwips
private static int CalcWidthOfRunInTwips(XElement r)
{
var fontName = (string)r.Attribute(PtOpenXml.pt + "FontName") ??
(string)r.Ancestors(W.p).First().Attribute(PtOpenXml.pt + "FontName");
if (fontName == null)
throw new OpenXmlPowerToolsException("Internal Error, should have FontName attribute");
if (UnknownFonts.Contains(fontName))
return 0;
var rPr = r.Element(W.rPr);
if (rPr == null)
throw new OpenXmlPowerToolsException("Internal Error, should have run properties");
var sz = GetFontSize(r) ?? 22m;
// unknown font families will throw ArgumentException, in which case just return 0
if (!KnownFamilies.Contains(fontName))
return 0;
// in theory, all unknown fonts are found by the above test, but if not...
FontFamily ff;
try
{
ff = new FontFamily(fontName);
}
catch (ArgumentException)
{
UnknownFonts.Add(fontName);
return 0;
}
var fs = FontStyle.Regular;
if (GetBoolProp(rPr, W.b) || GetBoolProp(rPr, W.bCs))
fs |= FontStyle.Bold;
if (GetBoolProp(rPr, W.i) || GetBoolProp(rPr, W.iCs))
fs |= FontStyle.Italic;
// Appended blank as a quick fix to accommodate that will get
// appended to some layout-critical runs such as list item numbers.
// In some cases, this might not be required or even wrong, so this
// must be revisited.
// TODO: Revisit.
var runText = r.DescendantsTrimmed(W.txbxContent)
.Where(e => e.Name == W.t)
.Select(t => (string) t)
.StringConcatenate() + " ";
var tabLength = r.DescendantsTrimmed(W.txbxContent)
.Where(e => e.Name == W.tab)
.Select(t => (decimal)t.Attribute(PtOpenXml.TabWidth))
.Sum();
if (runText.Length == 0 && tabLength == 0)
return 0;
int multiplier = 1;
if (runText.Length <= 2)
multiplier = 100;
else if (runText.Length <= 4)
multiplier = 50;
else if (runText.Length <= 8)
multiplier = 25;
else if (runText.Length <= 16)
multiplier = 12;
else if (runText.Length <= 32)
multiplier = 6;
if (multiplier != 1)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < multiplier; i++)
sb.Append(runText);
runText = sb.ToString();
}
try
{
using (Font f = new Font(ff, (float) sz/2f, fs))
{
const TextFormatFlags tff = TextFormatFlags.NoPadding;
var proposedSize = new Size(int.MaxValue, int.MaxValue);
var sf = TextRenderer.MeasureText(runText, f, proposedSize, tff);
// sf returns size in pixels
const decimal dpi = 96m;
var twip = (int) (((sf.Width/dpi)*1440m)/multiplier + tabLength*1440m);
return twip;
}
}
catch (ArgumentException)
{
try
{
const FontStyle fs2 = FontStyle.Regular;
using (Font f = new Font(ff, (float) sz/2f, fs2))
{
const TextFormatFlags tff = TextFormatFlags.NoPadding;
var proposedSize = new Size(int.MaxValue, int.MaxValue);
var sf = TextRenderer.MeasureText(runText, f, proposedSize, tff);
// sf returns size in pixels
const decimal dpi = 96m;
//.........這裏部分代碼省略.........
示例10: GetElementNamespace
/// <summary>
/// Gets an elements namespace.
/// </summary>
/// <param name="element">The element.</param>
/// <returns>
/// The element namespace.
/// </returns>
private static string GetElementNamespace(XElement element)
{
// Move up the tree to get the parent elements
var namespaces = element.Ancestors("test-suite").Where(x => x.Attribute("type").Value.ToLower() == "namespace");
// Get the namespace
return string.Join(".", namespaces.Select(x => x.Attribute("name").Value));
}
示例11: FindEnclosingClassElement
/// <summary>
/// Finds the nearest class or struct element that encloses the given element.
/// </summary>
/// <param name="startElement">The element from which to start looking for the enclosing class or struct.</param>
/// <returns>The nearest class or struct XElement that encloses the given element.
/// If there is no enclosing class or struct element, this function returns null.</returns>
private static XElement FindEnclosingClassElement(XElement startElement)
{
if (startElement == null) { return null; }
var ancestors = from a in startElement.Ancestors()
where a.Name == SRC.Class || a.Name == SRC.Struct
select a;
if (ancestors.Count() > 0)
{
return ancestors.First();
}
else
{
return null;
}
}
示例12: ConvertRun
//.........這裏部分代碼省略.........
}
else
{
style.AddIfMissing("font-weight", "normal");
}
// W.strike
if (getBoolProp(rPr, W.strike) || getBoolProp(rPr, W.dstrike))
{
var newContent = new XElement(Xhtml.s, content);
if (newContent.Nodes().Any())
content = newContent;
style.AddIfMissing("text-decoration", "line-through");
}
// W.vertAlign
if (rPr.Element(W.vertAlign) != null && (string)rPr.Elements(W.vertAlign).Attributes(W.val).FirstOrDefault() == "superscript")
{
var newContent = new XElement(Xhtml.sup, content);
if (newContent.Nodes().Any())
content = newContent;
}
if (rPr.Element(W.vertAlign) != null && (string)rPr.Elements(W.vertAlign).Attributes(W.val).FirstOrDefault() == "subscript")
{
var newContent = new XElement(Xhtml.sub, content);
if (newContent.Nodes().Any())
content = newContent;
}
var rtl = rPr.Element(W.rtl);
var isRtl = rtl != null;
var paragraph = run.Ancestors(W.p).FirstOrDefault();
var paraBidi = paragraph
.Elements(W.pPr)
.Elements(W.bidi)
.Where(b => b.Attribute(W.val) == null || b.Attribute(W.val).ToBoolean() == true)
.FirstOrDefault();
var paraIsBidi = paraBidi != null;
string lang = null;
if (languageType == "western")
lang = (string)rPr.Elements(W.lang).Attributes(W.val).FirstOrDefault();
else if (languageType == "bidi")
lang = (string)rPr.Elements(W.lang).Attributes(W.bidi).FirstOrDefault();
else if (languageType == "eastAsia")
lang = (string)rPr.Elements(W.lang).Attributes(W.eastAsia).FirstOrDefault();
// only do the following for text runs.
XEntity runStartMark = null;
XEntity runEndMark = null;
// Can't add directional marks if the font-family is symbol - they are visible, and display as a ?
bool addDirectionalMarks = true;
if (style.ContainsKey("font-family"))
{
if (style["font-family"].ToLower() == "symbol")
addDirectionalMarks = false;
}
if (addDirectionalMarks)
{
if (run.Element(W.t) != null)
{
if (isRtl)
{
示例13: ParseClassOrStruct
private ProgramElement ParseClassOrStruct(XElement cls, string fileName, bool parseStruct)
{
string name;
int definitionLineNumber;
int definitionColumnNumber;
SrcMLParsingUtils.ParseNameAndLineNumber(cls, out name, out definitionLineNumber, out definitionColumnNumber);
AccessLevel accessLevel = SrcMLParsingUtils.RetrieveAccessLevel(cls, AccessLevel.Public);
//parse namespace
IEnumerable<XElement> ownerNamespaces =
from el in cls.Ancestors(SRC.Declaration)
where el.Element(SRC.Type).Element(SRC.Name).Value == "namespace"
select el;
string namespaceName = String.Empty;
foreach (XElement ownerNamespace in ownerNamespaces)
{
foreach (XElement spc in ownerNamespace.Elements(SRC.Name))
{
namespaceName += spc.Value + " ";
}
}
namespaceName = namespaceName.TrimEnd();
//parse extended classes
string extendedClasses = String.Empty;
XElement super = cls.Element(SRC.Super);
if (super != null)
{
XElement implements = super.Element(SRC.Implements);
if (implements != null)
{
IEnumerable<XElement> impNames =
from el in implements.Descendants(SRC.Name)
select el;
foreach (XElement impName in impNames)
{
extendedClasses += impName.Value + " ";
}
extendedClasses = extendedClasses.TrimEnd();
}
}
string fullFilePath = System.IO.Path.GetFullPath(fileName);
string source = SrcMLParsingUtils.RetrieveSource(cls);
string body = cls.Value;
if (parseStruct)
{
return new StructElement(name, definitionLineNumber, definitionColumnNumber, fullFilePath, source, accessLevel, namespaceName, body, extendedClasses, String.Empty);
}
else
{
string implementedInterfaces = String.Empty;
return new ClassElement(name, definitionLineNumber, definitionColumnNumber, fullFilePath, source, accessLevel, namespaceName,
extendedClasses, implementedInterfaces, String.Empty, body);
}
}
示例14: ParseReferences
private static IEnumerable<Reference> ParseReferences(XNamespace ns, IEnumerable<XElement> referenceGroups, out XElement referencesNode)
{
referencesNode = referenceGroups.FirstOrDefault();
if (referencesNode != null)
{
referencesNode = referencesNode.Ancestors(ns + "ItemGroup").Single();
}
return ParseReferencesImpl(referenceGroups, ns);
}
示例15: ProcessContentControl
private static object ProcessContentControl(WordprocessingDocument wordDoc, HtmlConverterSettings settings,
XElement element, decimal currentMarginLeft)
{
var relevantAncestors = element.Ancestors().TakeWhile(a => a.Name != W.txbxContent);
var isRunLevelContentControl = relevantAncestors.Any(a => a.Name == W.p);
if (isRunLevelContentControl)
{
return element.Elements(W.sdtContent).Elements()
.Select(e => ConvertToHtmlTransform(wordDoc, settings, e, false, currentMarginLeft))
.ToList();
}
return CreateBorderDivs(wordDoc, settings, element.Elements(W.sdtContent).Elements());
}