public Style(XElement xElement) { foreach (XElement descendant in xElement.DescendantNodes()) { switch (descendant.Name.ToString()) { case "IconStyle": this.iconStyle = new IconStyle(descendant); break; //case "LabelStyle": // this.labelStyle = new LabelStyle(descendant); // break; //case "LineStyle": // this.lineStyle = new LineStyle(descendant); // break; //case "PolyStyle": // this.polyStyle = new PolyStyle(descendant); // break; //case "BalloonStyle": // this.balloonStyle = new BalloonStyle(descendant); // break; //case "ListStyle": // this.listStyle = new ListStyle(descendant); // break; } } }
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)); } }
public Option(XElement sourceElement, Service service) { Service = service; _texts = sourceElement .DescendantNodes() .OfType<XText>() .Where(t => !string.IsNullOrWhiteSpace(t.Value)) .Select(t => t.Value.Trim()) .ToList(); }
// ======================= Вспомогательные процедуры public static XElement DecodeTree(XElement tree) { // Найдем литералы и сделаем таблицу литералов int[] literals = tree.DescendantNodes() .Where(nd => nd.NodeType == System.Xml.XmlNodeType.Text) .Cast<XText>() .Where(xt => { int val; return Int32.TryParse(xt.Value, out val); }) .Select(xt => Int32.Parse(xt.Value)) .Distinct() .ToArray(); var lit_dict = RelationalEngine.GetLiteralsForIds(literals).ToDictionary(li => li.literalid); return DecTree(tree, lit_dict); }
public static XElement AddBatchMethod(XElement batch, string cmd, params object[] batchContent) { XElement method = new XElement("Method", new XAttribute("ID", batch.DescendantNodes().Count() + 1), new XAttribute("Cmd", cmd)); batch.Add(method); if (batchContent != null) { foreach (var item in batchContent) { method.Add(item); } } return method; }
private void FixWhitespace(XElement xmlElement) { foreach (var node in xmlElement.DescendantNodes()) { XElement el = node as XElement; if (el != null) { FixWhitespace(el); continue; } XText txt = node as XText; if (txt != null) { txt.Value = FixWhitespace(txt.Value); } } }
public static AmbientColor Create (XElement element, Dictionary<string, Cairo.Color> palette) { var result = new AmbientColor (); foreach (var node in element.DescendantNodes ()) { if (node.NodeType == System.Xml.XmlNodeType.Element) { var el = (XElement)node; switch (el.Name.LocalName) { case "name": result.Name = el.Value; break; default: result.Colors.Add (Tuple.Create (el.Name.LocalName, ColorScheme.ParsePaletteColor (palette, el.Value))); break; } } } return result; }
public void ExtractSettings(System.Xml.Linq.XElement pXElement) { foreach (XElement node in pXElement.DescendantNodes().OfType <XElement>()) { switch (node.Name.ToString()) { case XML_NODE_FORMAT: FormatTemplate = node.Value; break; case XML_NODE_REPLACE_UNDERSCORES: ReplaceUnderscores = GetBoolFromXml(node.Value); break; case XML_NODE_REPLACE_PERCENT_20: ReplacePercentTwenty = GetBoolFromXml(node.Value); break; } } }
private Dictionary<string, string> ExtractFeatureElements(XElement layerElement) { try { var feature = new Dictionary<string, string>(); var elements = layerElement.DescendantNodes().OfType<XElement>(); foreach (var element in elements) { if (!element.HasElements && !element.Name.LocalName.Equals("coordinates")) feature.Add(element.Name.LocalName, element.Value); } return feature; } catch (Exception) { throw new ApplicationException("Error creating features"); } }
public override void HandleExtendedParameters(XElement extendedParameters) { foreach (XElement param in extendedParameters.DescendantNodes()) { if(param.Name == "ParticleSystem") if (param.Attribute("name") != null) { if (!emitters.ContainsKey(param.Attribute("name").Value)) { if (param.Attribute("active") != null) { emitters.Add(param.Attribute("name").Value, bool.Parse(param.Attribute("active").Value)); } else { emitters.Add(param.Attribute("name").Value, true); } } } } }
private string AllInclusiveValue(XElement ele) { bool ignoreNext = false; return string.Join(" ", ele.DescendantNodes().Select(x => { if (ignoreNext) { ignoreNext = false; return null; } if (x is XText) return ((XText) x).Value; if (x is XElement) { var xele = (XElement) x; if (xele.IsEmpty) return "<" + xele.Name + "/>"; ignoreNext = true; return "<" + xele.Name + ">" + AllInclusiveValue(xele) + "</" + xele.Name + ">"; } return null; }).Where(x => x != null)); }
private object processMenuElement(XElement theElement, string theDefault, MenuItemClick delg) { if (theElement.Name == Common.MenuItem) { MenuItem theItem = new MenuItem(); theItem.Header = theElement.GetAttribute("text"); string action = theElement.GetAttribute(Common.MenuAction); theItem.Tag = action; if (action == theDefault) { theItem.FontWeight = FontWeights.Bold; } theItem.Click += new RoutedEventHandler(delg); /* theElement.GetAttribute("clientAction") if (Common.boolValue(theElement.GetAttribute("checked"))) theItem.Checked = true; if (theItem.Action == theDefault) theItem.DefaultItem = true; */ return theItem; } else if (theElement.Name == Common.ProcessSeparator) { Separator s = new Separator(); return s; } else//sub menu { MenuItem theItem = new MenuItem(); theItem.Header = theElement.Attribute("name").Value; foreach(XElement child in theElement.DescendantNodes() ) { theItem.Items.Add(processMenuElement((XElement)child, theDefault, delg)); } return theItem; } }
static void WriteXmlDocParameter(IXmlDocOutput output, XElement xml) { foreach (var elem in xml.DescendantNodes()) { if (elem is XText) output.Write(XmlDocRenderer.whitespace.Replace(((XText)elem).Value, " "), TextTokenType.XmlDocSummary); else if (elem is XElement) { var xelem = (XElement)elem; switch (xelem.Name.ToString().ToUpperInvariant()) { case "SEE": var cref = xelem.Attribute("cref"); if (cref != null) output.Write(XmlDocRenderer.GetCref((string)cref), TextTokenType.XmlDocToolTipSeeCref); var langword = xelem.Attribute("langword"); if (langword != null) output.Write(((string)langword).Trim(), TextTokenType.XmlDocToolTipSeeLangword); break; case "PARAMREF": var nameAttr = xml.Attribute("name"); if (nameAttr != null) output.Write(((string)nameAttr).Trim(), TextTokenType.XmlDocToolTipParamRefName); break; case "BR": case "PARA": output.WriteNewLine(); break; default: break; } } else output.Write(elem.ToString(), TextTokenType.XmlDocSummary); } }
/// <summary> /// Function inside the ModFileMerge of the Dragon Age gamemode. /// </summary> /// <param name="p_xeParentA">The first Xelement.</param> /// <param name="p_xeParentB">The second Xelement</param> /// <returns>Function inside the ModFileMerge of the Dragon Age gamemode.</returns> private static void MergeElements(XElement p_xeParentA, XElement p_xeParentB) { try { foreach (XElement childB in p_xeParentB.DescendantNodes()) { bool isMatchFound = false; foreach (XElement childA in p_xeParentA.Descendants()) { if ((!childA.Value.ToString().StartsWith("<!--")) || (!childB.Value.ToString().StartsWith("<!--"))) { if (AreEquivalent(childA, childB)) { MergeElements(childA, childB); isMatchFound = true; break; } } } if (!isMatchFound) p_xeParentA.Add(childB); } } catch { } }
private static void ResolveAssertContent(XElement xAssert, Assert assert, XmlNamespaceManager nsManager) { List<string> diagnostics = new List<string>(); List<bool> diagnosticsIsValueOf = new List<bool>(); XName nameElement = XName.Get("name", Constants.ISONamespace); XName valueofElement = XName.Get("value-of", Constants.ISONamespace); StringBuilder sbMessage = new StringBuilder(); foreach (XNode node in xAssert.DescendantNodes()) { if (!(node is XElement)) { sbMessage.Append(node.ToString()); } else { XElement xEle = (XElement)node; // resolve name, value-of string xpathDiagnostic = null; if (xEle.Name == nameElement) { diagnosticsIsValueOf.Add(false); xpathDiagnostic = "name()"; XAttribute xPath = xEle.Attribute(XName.Get("path")); if (xPath != null) { xpathDiagnostic = String.Format(String.Format("name({0})", xPath.Value)); } } else if (xEle.Name == valueofElement) { diagnosticsIsValueOf.Add(true); xpathDiagnostic = xEle.Attribute(XName.Get("select")).Value; } if (xpathDiagnostic != null) { // get collection index int index = diagnostics.IndexOf(xpathDiagnostic); if (index < 0) { diagnostics.Add(xpathDiagnostic); index = diagnostics.Count - 1; } sbMessage.Append("{"); sbMessage.Append(index); sbMessage.Append("}"); index++; } } } assert.Message = sbMessage.ToString(); assert.Diagnostics = diagnostics.ToArray(); assert.DiagnosticsIsValueOf = diagnosticsIsValueOf.ToArray(); }
internal static ChunkStyle Create (XElement element, Dictionary<string, HslColor> palette) { var result = new ChunkStyle (); foreach (var node in element.DescendantNodes ()) { if (node.NodeType == System.Xml.XmlNodeType.Element) { var el = (XElement)node; switch (el.Name.LocalName) { case "name": result.Name = el.Value; break; case "fore": result.Foreground = ColorScheme.ParsePaletteColor (palette, el.Value); break; case "back": result.Background = ColorScheme.ParsePaletteColor (palette, el.Value); break; case "weight": Xwt.Drawing.FontWeight weight; if (!Enum.TryParse<Xwt.Drawing.FontWeight> (el.Value, true, out weight)) throw new InvalidDataException (el.Value + " is no valid text weight values are: " + string.Join (",", Enum.GetNames (typeof(Xwt.Drawing.FontWeight))) ); result.FontWeight = weight; break; case "style": Xwt.Drawing.FontStyle style; if (!Enum.TryParse<Xwt.Drawing.FontStyle> (el.Value, true, out style)) throw new InvalidDataException (el.Value + " is no valid text weight values are: " + string.Join (",", Enum.GetNames (typeof(Xwt.Drawing.FontStyle))) ); result.FontStyle = style; break; default: throw new InvalidDataException ("Invalid element in text color:" + el.Name); } } } return result; }
/// <summary> /// Zakladni TRANS metoda: z HMLT vybere fragmenty k lokalizaci /// </summary> static IEnumerable<List<XNode>> transFragments(XElement root) { //Cyklus pres zakladni nodes: budto texty ktere nejsou v NOTRTANS a nebo vlastni NOTRANS foreach (XNode nd in from XNode n in root.DescendantNodes() where ( (n.NodeType == XmlNodeType.Text && n.Ancestors().Where(isTransElement()).Any() && !n.Ancestors().Where(isNoTransElement()).Any() && !n.Ancestors(html + "title").Any()) || (n.NodeType == XmlNodeType.Element && isNoTrans((XElement)n))) select n) ///... pro kazdy zakladni nodes anotaci oznac nejvyssiho parenta, ktery je jeste inline element foreach (XNode el in nd.AncestorsAndSelf()) if (!isInline(el.Parent)) { Anot.GetAnot(el).isBasic = true; break; } //cyklus pres parenty, obsahujici oznacene node //v techto parentech vybere souvisle useky z oznacenych childu List<XNode> res = new List<XNode>(); foreach (XElement el in root.DescendantNodes().Where(e => Anot.IsBasic(e)).Select(el => el.Parent).Distinct()) { bool inMarked = false; res.Clear(); foreach (XNode nd in el.Nodes()) { if (inMarked) { if (!Anot.IsBasic(nd)) { inMarked = false; normalizeList(res); if (res.Count > 0) { yield return res; res = new List<XNode>(); } } else res.Add(nd); } else { if (Anot.IsBasic(nd)) { res.Clear(); res.Add(nd); inMarked = true; } } } if (inMarked) { normalizeList(res); if (res.Count > 0) { yield return res; res = new List<XNode>(); } } } }
/// <summary> /// Serializes the xml element to a string. /// </summary> /// <param name="xml">The xml element to serialize.</param> /// <returns>The string representation of the xml.</returns> internal static string SerializeToString(XElement xml) { // because comment nodes can contain special characters that are hard to embed in VisualBasic, remove them here xml.DescendantNodes().OfType<XComment>().Remove(); var stringBuilder = new StringBuilder(); using (var writer = XmlWriter.Create( stringBuilder, new XmlWriterSettings { OmitXmlDeclaration = true, NewLineHandling = NewLineHandling.Replace, Indent = true })) { xml.WriteTo(writer); } return stringBuilder.ToString(); }
/// <summary> /// Create a NAntTarget from an Xml instance /// </summary> /// <param name="element">Element to load from</param> /// <returns>Newly constructed target.</returns> public static NAntTarget FromXml(XElement element) { Require.NotNull("element", element); if (!element.Name.LocalName.Equals("target")) { throw new ArgumentException("Expected <target> element", "element"); } var name = (string)element.Attribute("name"); var description = (string)element.Attribute("description") ?? string.Empty; var depends = (string)element.Attribute("depends") ?? string.Empty; var callers = element.DescendantNodes().Where(e => (e is XElement) && ((XElement) e).Name == "call"); var callerList = callers.Select(caller => (string) ((XElement) caller).Attribute("target") ?? ""); depends += string.Join(",", callerList); return new NAntTarget(name, description, depends); }
/// <summary> /// Validate enumeration of container descendents. /// </summary> /// <param name="contextValue"></param> /// <returns></returns> //[Variation(Desc = "ContainerDescendents")] public void ContainerDescendents() { XComment comment = new XComment("comment"); XElement level3 = new XElement("Level3"); XElement level2 = new XElement("Level2", level3); XElement level1 = new XElement("Level1", level2, comment); XElement level0 = new XElement("Level1", level1); Validate.EnumeratorDeepEquals( level1.Descendants(), new XElement[] { level2, level3 }); Validate.EnumeratorDeepEquals( level0.DescendantNodes(), new XNode[] { level1, level2, level3, comment }); Validate.EnumeratorDeepEquals(level0.Descendants(null), new XElement[0]); Validate.EnumeratorDeepEquals(level0.Descendants("Level1"), new XElement[] { level1 }); }
public static void Clean(XElement proj, IXmlNamespaceResolver ns, string relativeSigningKeyPath = null) { var frameworkVersion = "v4.5.2"; var frameworkProfile = ""; var configurations = new[] { "Debug", "Test", "Release" }; var platforms = new[] { "AnyCPU", "x86", "x64", "ARM" }; if (proj.Name.LocalName == "VisualStudioProject") return; #region Remove Cruft proj.XPathSelectElements("//build:AutorunEnabled", ns).Remove(); proj.XPathSelectElements("//build:PublishWizardCompleted", ns).Remove(); proj.XPathSelectElements("//build:TargetZone", ns).Remove(); proj.XPathSelectElements("//build:ApplicationManifest", ns).Remove(); proj.XPathSelectElements("//build:DefaultClientScript", ns).Remove(); proj.XPathSelectElements("//build:DefaultHTMLPageLayout", ns).Remove(); proj.XPathSelectElements("//build:DefaultTargetSchema", ns).Remove(); proj.XPathSelectElements("//build:FileUpgradeFlags", ns).Remove(); proj.XPathSelectElements("//build:OldToolsVersion", ns).Remove(); proj.XPathSelectElements("//build:UpgradeBackupLocation", ns).Remove(); proj.XPathSelectElements("//build:IsWebBootstrapper", ns).Remove(); proj.XPathSelectElements("//build:PublishUrl", ns).Remove(); proj.XPathSelectElements("//build:Install", ns).Remove(); proj.XPathSelectElements("//build:InstallFrom", ns).Remove(); proj.XPathSelectElements("//build:UpdateEnabled", ns).Remove(); proj.XPathSelectElements("//build:UpdateMode", ns).Remove(); proj.XPathSelectElements("//build:UpdateInterval", ns).Remove(); proj.XPathSelectElements("//build:UpdateIntervalUnits", ns).Remove(); proj.XPathSelectElements("//build:UpdatePeriodically", ns).Remove(); proj.XPathSelectElements("//build:UpdateRequired", ns).Remove(); proj.XPathSelectElements("//build:MapFileExtensions", ns).Remove(); proj.XPathSelectElements("//build:ApplicationRevision", ns).Remove(); proj.XPathSelectElements("//build:ApplicationVersion", ns).Remove(); proj.XPathSelectElements("//build:UseApplicationTrust", ns).Remove(); proj.XPathSelectElements("//build:BootstrapperEnabled", ns).Remove(); proj.XPathSelectElements("//build:BootstrapperPackage", ns).Remove(); proj.XPathSelectElements("//build:SccProjectName", ns).Remove(); proj.XPathSelectElements("//build:SccLocalPath", ns).Remove(); proj.XPathSelectElements("//build:SccAuxPath", ns).Remove(); proj.XPathSelectElements("//build:SccProvider", ns).Remove(); proj.XPathSelectElements("//build:NuGetPackageImportStamp", ns).Remove(); proj.XPathSelectElements("//build:NoWin32Manifest", ns).Remove(); proj.XPathSelectElements("//build:EnableSecurityDebugging", ns).Remove(); proj.XPathSelectElements("//build:StartAction", ns).Remove(); proj.XPathSelectElements("//build:HostInBrowser", ns).Remove(); proj.XPathSelectElements("//build:CreateWebPageOnPublish", ns).Remove(); proj.XPathSelectElements("//build:WebPage", ns).Remove(); proj.XPathSelectElements("//build:OpenBrowserOnPublish", ns).Remove(); proj.XPathSelectElements("//build:TrustUrlParameters", ns).Remove(); proj.XPathSelectElements("//build:UseIISExpress", ns).Remove(); proj.XPathSelectElements("//build:IISExpressSSLPort", ns).Remove(); proj.XPathSelectElements("//build:IISExpressAnonymousAuthentication", ns).Remove(); proj.XPathSelectElements("//build:IISExpressWindowsAuthentication", ns).Remove(); proj.XPathSelectElements("//build:IISExpressUseClassicPipelineMode", ns).Remove(); #endregion proj.DescendantNodes().OfType<XComment>().Where(c => c.Value.Contains("<Target Name=\"BeforeBuild\">")).Remove(); #region Remove Folders proj.XPathSelectElements(@"//build:Folder", ns).Remove(); #endregion #region Clean up main PropertyGroup proj.SetAttributeValue("ToolsVersion", "14.0"); var mainPG = proj.XPathSelectElement("//build:PropertyGroup[build:ProjectGuid]", ns); proj.XPathSelectElements("//build:ProjectType", ns).Remove(); proj.XPathSelectElements("//build:ProductVersion", ns).Remove(); proj.XPathSelectElements("//build:SchemaVersion", ns).Remove(); proj.XPathSelectElements("//build:StartupObject", ns).Where(e => String.IsNullOrWhiteSpace(e.Value)).Remove(); proj.XPathSelectElements("//build:ApplicationIcon", ns).Where(e => String.IsNullOrWhiteSpace(e.Value)).Remove(); proj.XPathSelectElements("//build:PropertyGroup[build:ProjectGuid]/build:FileAlignment", ns).Remove(); proj.XPathSelectElements("//build:PropertyGroup[build:ProjectGuid]/build:WarningLevel", ns).Remove(); proj.XPathSelectElements("//build:ApplicationIcon", ns).Reparent(mainPG); proj.XPathSelectElements("//build:ResolveAssemblyWarnOrErrorOnTargetArchitectureMismatch", ns).Reparent(mainPG); if (frameworkVersion != null) { proj.XPathSelectElements("//build:TargetFrameworkVersion", ns).SetValue(frameworkVersion); if (!string.IsNullOrEmpty(frameworkProfile)) proj.XPathSelectElements("//build:TargetFrameworkProfile", ns).SetValue(frameworkProfile); else proj.XPathSelectElements("//build:TargetFrameworkProfile", ns).Nodes().Remove(); } proj.XPathSelectElements("//build:ProjectTypeGuids", ns).SetValue(e => e.ToLower()); var mainOrder = new[] { "Configuration", "Platform", "ProjectGuid", "ProjectTypeGuids", "OutputType", "AppDesignerFolder", "RootNamespace", "AssemblyName", "TargetFrameworkVersion", "TargetFrameworkProfile", "AutoGenerateBindingRedirects", "ApplicationIcon", }; mainPG.Elements().OrderBy(x => IndexOf(mainOrder, x.Name.LocalName) ?? Int32.MaxValue).Reparent(mainPG); #endregion #region Sort Configuration items var pcOrder = platforms.SelectMany(p => configurations.Select(c => String.Format("'{0}|{1}'", c, p))).ToArray(); var cpgOrder = new[] { "PlatformTarget", "DebugSymbols", "DebugType", "Optimize", "OutputPath", "DefineConstants", "ErrorReport", "WarningLevel", "AllowUnsafeBlocks", "BaseAddress", "CheckForOverflowUnderflow", "ConfigurationOverrideFile", "DocumentationFile", "FileAlignment", "NoStdLib", "NoWarn", "RegisterForComInterop", "RemoveIntegerChecks", "TreatWarningsAsErrors", "UseVSHostingProcess", "CodeAnalysisIgnoreBuiltInRuleSets", "CodeAnalysisIgnoreBuiltInRules", "RunCodeAnalysis", }; proj.XPathSelectElements("//*[contains(@Condition, '$(Configuration)|$(Platform)')]", ns).Where(e => !pcOrder.Any(o => e.Attribute("Condition").Value.Contains(o))).Remove(); foreach (var grouping in proj.XPathSelectElements("//*[contains(@Condition, '$(Configuration)|$(Platform)')]", ns).GroupBy(e => new { p = e.Parent, en = e.Name.LocalName })) { var previous = grouping.First().PreviousNode; var children = grouping.OrderBy(e => IndexOf(pcOrder, o => e.Attribute("Condition").Value.Contains(o)) ?? Int32.MaxValue).ThenBy(e => e.Attribute("Condition").Value.Trim()).ToArray(); children.Remove(); previous.AddAfterSelf(children); foreach (var cgp in children.Where(e => e.Name.LocalName == "PropertyGroup")) { cgp.Elements().OrderBy(e => IndexOf(cpgOrder, e.Name.LocalName) ?? Int32.MaxValue).Reparent(cgp); } continue; } proj.XPathSelectElements("//build:DefineConstants", ns).SetValue(e => String.Join(";", e.Value.Split(';').OrderBy(v => v.TrimStart('_')).ThenBy(v => v))); #endregion #region Clean up Items proj.XPathSelectElements("//build:SubType", ns).Where(s => String.IsNullOrWhiteSpace(s.Value)).Remove(); proj.XPathSelectElements("//*[@Include='app.config']/build:SubType", ns).Remove(); proj.XPathSelectElements("//build:Compile/build:SubType[text()='Code']", ns).Remove(); var noDesigner = new[] { ".config", ".xml", ".xsd", ".xslt", ".ejs" }; proj.XPathSelectElements("//build:*[@Include]/build:SubType[text()='Designer']", ns).Where(s => noDesigner.Contains(Path.GetExtension(s.Parent.Attribute("Include").Value), StringComparer.InvariantCultureIgnoreCase)).Remove(); foreach (var item in proj.XPathSelectElements("//build:*[@Include]", ns).Where(e => e.Attribute("Include").Value.EndsWith(".xaml", StringComparison.InvariantCultureIgnoreCase) && e.Name.LocalName != "Reference")) { item.XPathSelectElements(".//build:Generator", ns).Remove(); item.XPathSelectElements(".//build:SubType", ns).Remove(); item.AddElement("Generator", content: "MSBuild:Compile", first: true); item.AddElement("SubType", content: "Designer", first: true); } var itemTypes = new[] { "Compile", "Content", "Resource", "EmbeddedResource", "None", "ApplicationDefinition", "Page", "SplashScreen" }; var items = proj.XPathSelectElements("//build:*[@Include]", ns).Where(e => itemTypes.Contains(e.Name.LocalName)).OrderBy(e => e.Attribute("Include").Value).ToArray(); foreach (var item in items.Where(e => !e.IsEmpty && !e.HasElements)) { item.RemoveNodes(); } #endregion #region Clean up References proj.XPathSelectElements("//build:Reference[@Include='System.configuration']", ns).Attributes("Include").SetValue("System.Configuration"); proj.XPathSelectElements("//build:Reference[@Include='System.XML']", ns).Attributes("Include").SetValue("System.Xml"); proj.XPathSelectElements("//build:AssemblyFolderKey", ns).Remove(); proj.XPathSelectElements("//build:SpecificVersion", ns).Remove(); proj.XPathSelectElements("//build:ReferencePath", ns).Remove(); proj.XPathSelectElements("//build:CurrentPlatform", ns).Remove(); proj.XPathSelectElements("//build:Reference/build:Name", ns).Remove(); proj.XPathSelectElements("//build:Reference/build:RequiredTargetFramework", ns).Remove(); var referenceParent = proj.XPathSelectElements("//build:ItemGroup[build:Reference]", ns).FirstOrDefault(); if (referenceParent != null) { proj.XPathSelectElements("//build:Reference", ns).OrderBy(c => c.Attribute("Include").Value.SubstringTill(',').Replace("System", "aaaaaaa")).Reparent(referenceParent); } #endregion #region Clean up ProjectReferences proj.XPathSelectElements("//build:ProjectReference/build:Package", ns).Remove(); proj.XPathSelectElements("//build:ProjectReference[@Include]/build:Name", ns).SetValue(n => Path.GetFileNameWithoutExtension(n.Parent.Attribute("Include").Value)); foreach (var name in proj.XPathSelectElements("//build:ProjectReference[@Include]/build:Name", ns)) { var parent = name.Parent; name.Remove(); parent.AddFirst(name); } var projectReferenceParent = proj.XPathSelectElements("//build:ItemGroup[build:ProjectReference]", ns).FirstOrDefault(); if (projectReferenceParent != null) { proj.XPathSelectElements("//build:ProjectReference", ns).OrderBy(c => c.Element(XName.Get("Name", ns.LookupNamespace("build"))).Value).Reparent(projectReferenceParent); } var imports = proj.XPathSelectElements("//build:Import[starts-with(@Project, '..')]", ns).ToArray(); foreach (var import in imports) { var path = import.Attribute("Project").Value; import.SetAttributeValue("Condition", String.Format("Exists('{0}')", path)); continue; } #endregion #region Clean up Web Projects proj.XPathSelectElements("//build:SaveServerSettingsInUserFile", ns).SetValue(true); proj.XPathSelectElements("//build:WebProjectProperties/build:UseIIS", ns).Remove(); proj.XPathSelectElements("//build:WebProjectProperties/build:AutoAssignPort", ns).Remove(); proj.XPathSelectElements("//build:WebProjectProperties/build:DevelopmentServerPort", ns).Remove(); proj.XPathSelectElements("//build:WebProjectProperties/build:DevelopmentServerVPath", ns).Remove(); proj.XPathSelectElements("//build:WebProjectProperties/build:IISUrl", ns).Remove(); proj.XPathSelectElements("//build:WebProjectProperties/build:NTLMAuthentication", ns).Remove(); proj.XPathSelectElements("//build:WebProjectProperties/build:UseCustomServer", ns).Remove(); proj.XPathSelectElements("//build:WebProjectProperties/build:CustomServerUrl", ns).Remove(); #endregion #region Clean up PreBuildEvent/PostBuildEvent proj.XPathSelectElements("//build:PostBuildEvent", ns).Where(e => e.Value.IndexOf("sn.exe", StringComparison.CurrentCultureIgnoreCase) >= 0).SetValue(""); proj.XPathSelectElements("//build:PreBuildEvent", ns).Where(e => String.IsNullOrWhiteSpace(e.Value)).Remove(); proj.XPathSelectElements("//build:PostBuildEvent", ns).Where(e => String.IsNullOrWhiteSpace(e.Value)).Remove(); if (!proj.XPathSelectElements("//build:PreBuildEvent", ns).Any(e => String.IsNullOrWhiteSpace(e.Value))) proj.XPathSelectElements("//build:RunPreBuildEvent", ns).Remove(); if (!proj.XPathSelectElements("//build:PostBuildEvent", ns).Any(e => String.IsNullOrWhiteSpace(e.Value))) proj.XPathSelectElements("//build:RunPostBuildEvent", ns).Remove(); #endregion #region Configure signing var canSign = !String.IsNullOrEmpty(relativeSigningKeyPath); proj.XPathSelectElements("//build:SignAssembly", ns).Remove(); proj.XPathSelectElements("//build:DelaySign", ns).Remove(); proj.XPathSelectElements("//build:AssemblyOriginatorKeyFile", ns).Remove(); proj.XPathSelectElements("//build:AssemblyKeyContainerName", ns).Remove(); if (mainPG != null) { mainPG.AddElement("SignAssembly", content: canSign); if (canSign) { mainPG.AddElement("DelaySign", content: false); mainPG.AddElement("AssemblyOriginatorKeyFile", content: relativeSigningKeyPath); } } #endregion proj.XPathSelectElements("//build:PropertyGroup", ns).Where(e => !e.Nodes().Any()).Remove(); proj.XPathSelectElements("//build:ItemGroup", ns).Where(e => !e.Nodes().Any()).Remove(); }
private void CreateReferenceFiles(IEnumerable<KeyValuePair<string, IEnumerable<XElement>>> allReferences, IEnumerable<XElement> dependencies, XElement filesElement) { var xElements = allReferences.SelectMany(pair => pair.Value).DistinctBy(element => element.Attribute("Include").Value); var elements = xElements.Except(dependencies).Except(filesElement.Elements()); foreach (var assemblyName in elements.Select(GetAssemblyName)){ var newFileElement = NewFileElement(assemblyName); if (filesElement.DescendantNodes().Cast<XElement>().All(element => element.Attribute("src").Value != newFileElement.Attribute("src").Value)) { filesElement.Add(newFileElement); } } }
/// <summary> /// Function inside the ModFileMerge of the Dragon Age gamemode. /// </summary> /// <param name="p_xeParentA">The first Xelement.</param> /// <param name="p_xeParentB">The second Xelement</param> /// <returns>Function inside the ModFileMerge of the Dragon Age gamemode.</returns> private static void MergeElements(XElement p_xeParentA, XElement p_xeParentB) { try { foreach (XElement childB in p_xeParentB.DescendantNodes()) { bool isMatchFound = false; foreach (XElement childA in p_xeParentA.Descendants()) { if (AreEquivalent(childA, childB)) { MergeElements(childA, childB); isMatchFound = true; break; } } if (!isMatchFound) p_xeParentA.Add(childB); } } catch { } }
public static void CheckElements(XElement exported, XElement desired) { if (exported.Name.LocalName != desired.Name.LocalName) Feedback.Add(new Feedback { FeedbackType = FeedbackType.Error, ExportedNode = exported, DesiredNode = desired, Message = "Element names are different" }); // Check text value of leaf nodes if (!exported.HasElements && !desired.HasElements) { var exportedValue = exported.DescendantNodes().OfType<XText>().Select(x => x.Value).FirstOrDefault(); var desiredValue = desired.DescendantNodes().OfType<XText>().Select(x => x.Value).FirstOrDefault(); if (exportedValue != desiredValue) Feedback.Add(new Feedback { FeedbackType = FeedbackType.Error, ExportedNode = exported, DesiredNode = desired, Message = "Text values are different" }); } CheckAttributes(exported, desired); }
static void ExpandTemplates(XDocument doc, List<XElement> templates) { foreach (var inheritMarker in doc.Descendants("inherittemplate").ToList()) { var name = inheritMarker.Attribute("name").Value; var replacement = inheritMarker.Attribute("replacement")?.Value; var template = templates.Single(t => t.Attribute("name").Value == name); var clonedTemplate = new XElement(template); if (replacement != null) { foreach (var attribute in clonedTemplate.Descendants().Attributes()) { attribute.Value = attribute.Value.Replace(name, replacement); } foreach (var text in clonedTemplate.DescendantNodes().OfType<XText>()) { text.Value = text.Value.Replace(name, replacement); } } inheritMarker.ReplaceWith(clonedTemplate.Elements()); } }
public void ContainerDescendents() { XComment comment = new XComment("comment"); XElement level3 = new XElement("Level3"); XElement level2 = new XElement("Level2", level3); XElement level1 = new XElement("Level1", level2, comment); XElement level0 = new XElement("Level1", level1); Assert.Equal(new XElement[] { level2, level3 }, level1.Descendants(), XNode.EqualityComparer); Assert.Equal( new XNode[] { level1, level2, level3, comment }, level0.DescendantNodes(), XNode.EqualityComparer); Assert.Empty(level0.Descendants(null)); Assert.Equal(new XElement[] { level1 }, level0.Descendants("Level1"), XNode.EqualityComparer); }
public static void setText(XElement root) { //Kontrola, zdali vsechny tagy obsahuji ID nebo id if (tags(root, true).Where(el => id(el) == null).Any()) throw new Exception("Some <asp:???> tag in TransBlock has not ID: " + root.ToString()); //Kopie TransBlock XElement textRoot = XElement.Parse(root.ToString()); textRoot.Add(new XAttribute("xmlns", "htmlPassivePage")); foreach (XElement el in textRoot.Descendants()) { XAttribute attr = el.Attribute("xmlns"); if (attr != null) attr.Remove(); } //Nahrada tagu foreach (XElement asp in tags(textRoot, true).ToArray()) { XElement span = new XElement(TradosLib.html + "span", new XAttribute("class", id(asp))); asp.AddAfterSelf(span); asp.Remove(); switch (asp.Name.LocalName) { case "PlaceHolder": break; case "HyperLink": span.Add(new XText(asp.Attribute("Text").Value)); break; case "a": span.Add(new XText(asp.Value)); break; } } //Ulozeni kopie do Text atributu root.Add(new XAttribute("Text", innerXml(textRoot.ToString()))); //V puvodnim tagu: TransVersion=true root.Add(new XAttribute("TransVersion", "true")); //V puvodnim tagu: vymazani vsech text nodes: foreach (XText txt in root.DescendantNodes().Where(nd => nd is XText && !inPlaceHolder(root, nd)).ToArray()) txt.Remove(); //V puvodnim tagu: vymazani vsech inline tagu foreach (XElement asp in tags(root, false).Where(el => !inPlaceHolder(root, el)).ToArray()) { asp.AddAfterSelf(asp.Nodes()); asp.Remove(); } //V puvodnim tagu: vymazani lokalizovanych atributu foreach (XElement asp in tags(root, true).ToArray()) { switch (asp.Name.LocalName) { case "HyperLink": asp.Attribute("Text").Remove(); break; } } }