public override void Execute(XElement el){ string code = el.Attr("code"); Type type = Type.GetType(code, false); if (null == type){ _project.Log.Error("Не могу найти расширение - генератор с именем " + code); return; } var gen = Activator.CreateInstance(type) as ISourceCodeGenerator; if (null == gen){ _project.Log.Error("Указанный класс " + code + " не соответствует интерфейсу ISourceCodeGenerator"); return; } IEnumerable<XNode> replaces = null; try{ replaces = gen.Execute(_project, el, null).ToArray(); } catch (Exception ex){ _project.Log.Error("Ошибка при вызове " + gen.GetType().Name + " на " + el, ex); return; } if (!replaces.Any()){ el.Remove(); } else{ el.ReplaceWith(replaces.OfType<object>().ToArray()); } }
private static void HandleStringElement(XElement element) { XAttribute attribute = element.Attribute("key"); if (attribute == null) throw new InvalidOperationException(string.Format("Missing attibute named 'key' at {0}", element)); string newValue = StringResourceSystemFacade.ParseString(string.Format("${{{0}}}", attribute.Value)); element.ReplaceWith(newValue); }
/// <summary> /// Resolves the condition. /// </summary> /// <param name="e"> The e. </param> /// <param name="id"> The id. </param> /// <remarks> /// </remarks> private void ResolveCondition(XElement e, string id) { if (!Match(id)) { e.Remove(); return; } foreach (var a in e.Attributes()) { SetParentAttribute(e, a); } e.ReplaceWith(e.Elements()); }
/// <summary> /// Replaces the first element with the same name or adds a new element. /// </summary> /// <param name="this">This parent element.</param> /// <param name="e">The element wthat will replace its first homonym or be added.</param> /// <returns>This element.</returns> public static XElement ReplaceElementByName(this XElement @this, XElement e) { XElement c = @this.Element(e.Name); if (c == null) { @this.Add(e); } else { c.ReplaceWith(e); } return(e); }
/// <summary> /// executes generator /// </summary> /// <param name="context"> </param> /// <param name="callelement"> </param> public void Execute(ThemaCompilerContext context, XElement callelement) { var generator = Activator.CreateInstance(Type) as IThemaXmlGenerator; if (generator is IThemaCompileTimeGenerator) { callelement.ReplaceWith(((IThemaCompileTimeGenerator) generator).Generate(callelement, context).ToArray()); } else { if (generator != null) { callelement.ReplaceWith(generator.Generate(callelement).ToArray()); } } }
/// <summary> /// Apply the formatting from a span including all nested spans to each run contained within it /// </summary> /// <param name="span">The root span from which to start applying formatting</param> /// <param name="runProps">The run properties in which to accumulate formatting</param> private static void ApplySpanFormatting(XElement span, XElement runProps) { string spanClass = (string)span.Attribute("class"); switch(spanClass) { case null: // Missing class name, ignore it. Shouldn't see any at this point, but just in case. break; case "languageSpecificText": // Replace language-specific text with the neutral text sub-entry. If not found, remove it. var genericText = span.Elements("span").FirstOrDefault(s => (string)s.Attribute("class") == "nu"); if(genericText != null) span.ReplaceWith(new XElement(w + "r", new XElement(w + "t", genericText.Value))); else span.Remove(); return; case "Bold": case "nolink": case "NoLink": case "selflink": case "SelfLink": if(!runProps.Elements(w + "b").Any()) runProps.Add(new XElement(w + "b")); break; case "Emphasis": if(!runProps.Elements(w + "i").Any()) runProps.Add(new XElement(w + "i")); break; case "Underline": if(!runProps.Elements(w + "u").Any()) runProps.Add(new XElement(w + "u", new XAttribute(w + "val", "single"))); break; case "Subscript": // If vertAlign exists, replace it as we can't merge it var subscript = runProps.Elements(w + "vertAlign").FirstOrDefault(); if(subscript != null) subscript.Attribute(w + "val").Value = "subscript"; else runProps.Add(new XElement(w + "vertAlign", new XAttribute(w + "val", "subscript"))); break; case "Superscript": // If vertAlign exists, replace it as we can't merge it var superscript = runProps.Elements(w + "vertAlign").FirstOrDefault(); if(superscript != null) superscript.Attribute(w + "val").Value = "superscript"; else runProps.Add(new XElement(w + "vertAlign", new XAttribute(w + "val", "superscript"))); break; default: // Named style // Correct the casing on code and syntax section style names switch(spanClass) { case "comment": case "identifier": case "keyword": case "literal": case "parameter": case "typeparameter": spanClass = spanClass[0].ToString().ToUpperInvariant() + spanClass.Substring(1); break; default: break; } // If one exists, replace it since we can't merge them var namedStyle = runProps.Elements(w + "rStyle").FirstOrDefault(); if(namedStyle != null) namedStyle.Attribute(w + "val").Value = spanClass; else runProps.Add(new XElement(w + "rStyle", new XAttribute(w + "val", spanClass))); break; } // If the span does not have children but is not empty, it has inner text that needs to be wrapped // in a run. if(!span.HasElements && !span.IsEmpty) { var content = new XElement(w + "r", new XElement(w + "t", new XAttribute(XNamespace.Xml + "space", "preserve"), span.Value)); span.Value = String.Empty; span.Add(content); } // Add the run properties to each child run foreach(var run in span.Elements(w + "r")) run.AddFirst(new XElement(runProps)); // Handle nested spans. These will accumulate the formatting of the parent spans. foreach(var nestedSpan in span.Elements("span").ToList()) ApplySpanFormatting(nestedSpan, new XElement(runProps)); // Now move the content up to the parent foreach(var child in span.Nodes().ToList()) { child.Remove(); span.AddBeforeSelf(child); } // And finally, remove the span span.Remove(); }
private void DeQueueMerges(XDocument main, Dictionary<string, XElement> idDictionary) { if (idDictionary.Keys.FirstOrDefault() == null) return; // We're not needed here. Log.Info("Applying base elements."); XElement mainElement = main.Root.Elements("RulesElement").First(); XNode NextElement; do { XNode prev = mainElement.PreviousNode; NextElement = mainElement.NextNode; while (NextElement != null && !(NextElement is XElement)) NextElement = NextElement.NextNode; string id = getID(mainElement); if (idDictionary.ContainsKey(id)) { foreach (XElement partElement in idDictionary[id].Elements()) { switch (partElement.Name.LocalName) { case "RulesElement": mainElement.ReplaceWith(partElement); break; case "RemoveNodes": removeElement(partElement, mainElement); break; case "AppendNodes": appendToElement(partElement, mainElement); break; case "DeleteElement": deleteElement(partElement, mainElement); break; } mainElement = prev.NextNode as XElement; // Lost Parent } idDictionary.Remove(id); } if (idDictionary.ContainsKey("nullID")) { XElement[] MassAppends = idDictionary["nullID"].Elements().ToArray(); for (int i = 0; i < MassAppends.Length; i++) { XElement partElement = MassAppends[i]; string[] ids = partElement.Attribute("ids").Value.Trim().Split(','); if (ids.Contains(id)) appendToElement(partElement, mainElement); } } if (idDictionary.Keys.FirstOrDefault() == null) return; // Quick way of aborting if we're done. Anything more complex isn't really worth it. } while ((mainElement = NextElement as XElement) != null); Log.Info("Applying new elements"); foreach (String id in idDictionary.Keys.ToArray()) { XElement RulesCollection = idDictionary[id]; mainElement = new XElement("RulesElement", new XAttribute("internal-id","deleteme")); main.Root.Add(mainElement); XNode prev = mainElement.PreviousNode; foreach (XElement partElement in RulesCollection.Elements()) { switch (partElement.Name.LocalName) { case "RulesElement": mainElement.ReplaceWith(partElement); break; case "RemoveNodes": removeElement(partElement, mainElement); break; case "AppendNodes": appendToElement(partElement, mainElement); break; case "DeleteElement": deleteElement(partElement, mainElement); break; } mainElement = prev.NextNode as XElement; // Lost Parent } if (getID(mainElement) == "deleteme") mainElement.Remove(); // It was only an append. idDictionary.Remove(id); } }
private void ControlElement(XElement root, XElement currentElement) { if (GetLineLength(root) > LengthLimit) { if (!HasGrandChildren(currentElement)) { currentElement.ReplaceWith(CreateEntirelyFoldedElement(currentElement)); return; } var children = currentElement.Elements().ToArray(); for (int i = children.Count() - 1; i >= 0; i--) { var child = children.ElementAt(i); ControlElement(root, child); if (GetLineLength(root) <= LengthLimit) return; } currentElement.ReplaceWith(CreateEntirelyFoldedElement(currentElement)); } }
private void ReplaceIReadDefines(XElement annotation) { annotation.ReplaceWith( from type in _Types.GetInterfaceTypes("IReadDefines") let name = MagickTypes.GetXsdName(type) select new XElement(_Namespace + "element", new XAttribute("name", name), new XAttribute("type", name))); }
private void ReplaceDefines(XElement annotation) { List<XElement> types = new List<XElement>(); foreach (Type interfaceType in _Types.GetInterfaceTypes("IDefines")) { XElement complexType = new XElement(_Namespace + "complexType", new XAttribute("name", MagickTypes.GetXsdName(interfaceType))); AddClass(complexType, interfaceType); types.Add(complexType); } annotation.ReplaceWith(types.ToArray()); }
/// <summary> /// Replaces the parameter. /// </summary> /// <param name="pr"> The pr. </param> /// <param name="code"> The code. </param> /// <remarks> /// </remarks> private void ReplaceParameter(XElement pr, string code) { var p = Context.ParameterIndex[code]; if (null == p.Annotation<UsedInWorkingThemaAnnotation>()) { p.AddAnnotation(UsedInWorkingThemaAnnotation.Default); } p = new XElement(p); if (pr.Name.LocalName == "use") { var list = p.Attribute("list"); if (null != list) { list.Remove(); } } foreach (var a in pr.Attributes() .Where(a => !a.Name.LocalName.EndsWith("list") || pr.Name.LocalName != "use")) { p.SetAttributeValue(a.Name, a.Value); } if (!string.IsNullOrEmpty(pr.Value)) { p.Value = pr.Value; } if (null != p.Attribute("clear")) { p.Value = ""; } switch (pr.Name.LocalName) { case "ask": p.Name = "var"; break; case "use": p.Name = "param"; break; } pr.ReplaceWith(p); }
private static void ReplaceAbstractPatternInstance(Dictionary<string, XElement> dicAPs, XElement xInstance, XmlNamespaceManager nsManager) { // select is-a string isa = xInstance.Attribute(XName.Get("is-a")).Value; // select id string id = null; XAttribute xAttId = xInstance.Attribute(XName.Get("id")); if (xAttId != null) { id = xAttId.Value; } // select params XName paramName = XName.Get("param", Constants.ISONamespace); Dictionary<string, Parameter> dicParams = new Dictionary<string, Parameter>(); foreach (XElement xParam in xInstance.Descendants()) { if (xParam.Name == paramName) { Parameter param = new Parameter(); param.Name = String.Concat("$", xParam.Attribute(XName.Get("name")).Value); param.Value = xParam.Attribute(XName.Get("value")).Value; dicParams.Add(param.Name, param); } } XElement newPattern = new XElement(dicAPs[isa]); // remove abstract attribute newPattern.Attribute(XName.Get("abstract")).Remove(); // alter id attribute if (id != null) { newPattern.SetAttributeValue(XName.Get("id"), id); } else { newPattern.Attribute(XName.Get("id")).Remove(); } // transform rules foreach (XElement xRule in newPattern.XPathSelectElements("//sch:rule[@context]", nsManager)) { XAttribute xContext = xRule.Attribute(XName.Get("context")); string context = xContext.Value; foreach (KeyValuePair<string, Parameter> item in dicParams) { context = context.Replace(item.Value.Name, item.Value.Value); } xContext.Value = context; } // transform asserts foreach (XElement xAssert in newPattern.XPathSelectElements("//sch:assert|//sch:report ", nsManager)) { XAttribute xTest = xAssert.Attribute(XName.Get("test")); string test = xTest.Value; foreach (KeyValuePair<string, Parameter> item in dicParams) { test = test.Replace(item.Value.Name, item.Value.Value); } xTest.Value = test; } xInstance.ReplaceWith(newPattern); }
static bool ProcessXamlForDisplay(string sourceXaml, string sourceXamlFileNameAndPath, EnvDTE.Project currentProject, EnvDTE.Solution currentSolution, Dictionary <string, EnvDTE.Project> assemblyNameToProjectDictionary, ResourcesCache resourcesCache, out string outputXaml, out string errorsIfAny, out HashSet <string> warningsAndTips) { warningsAndTips = new HashSet <string>(); // Default output values: outputXaml = sourceXaml; errorsIfAny = ""; //--------------------------------------- // Remove the content of all the "HtmlPresenter" nodes, because the content may be not well formatted and may lead to a syntax error when parsing the XDocument: //--------------------------------------- sourceXaml = HtmlPresenterRemover.RemoveHtmlPresenterNodes(sourceXaml); //--------------------------------------- // Read the XDocument: //--------------------------------------- System.Xml.Linq.XDocument xdoc; try { xdoc = System.Xml.Linq.XDocument.Parse(sourceXaml); } catch (Exception ex) { errorsIfAny = ex.Message; return(false); } //--------------------------------------- // Remove the "x:Class" attribute if any: //--------------------------------------- if (xdoc.Root != null) { // Remove the "x:Class" attribute if any: XNamespace xNamespace = "http://schemas.microsoft.com/winfx/2006/xaml"; XAttribute classAttributeIfAny = xdoc.Root.Attribute(xNamespace + "Class"); if (classAttributeIfAny != null) { classAttributeIfAny.Remove(); } } //--------------------------------------- // Replace the root control with a UserControl (if it is not already one) and keep only the properties and attributes supported by the UserControl class: //--------------------------------------- ProcessNodeToMakeItCompatibleWithWpf.ReplaceRootWithUserControl(xdoc); //--------------------------------------- // Get the styles and other resources defined in App.xaml //--------------------------------------- IEnumerable <XElement> appDotXamlResources; string appDotXamlFullPath; if (resourcesCache.AppDotXamlResources != null) // This avoids reloading App.xaml at every refresh, to improve performance. { // Read from cache: appDotXamlResources = resourcesCache.AppDotXamlResources; appDotXamlFullPath = resourcesCache.AppDotXamlFullPath; } else { // Attempt to find App.xaml and read it: appDotXamlResources = ResolvingReferencedXamlResources.GetAppDotXamlResources(currentProject, currentSolution, out appDotXamlFullPath); resourcesCache.AppDotXamlResources = appDotXamlResources; resourcesCache.AppDotXamlFullPath = appDotXamlFullPath; } //--------------------------------------- // Resolve all the "Merged Dictionaries", and merge them so that there are no more references to other XAML files: //--------------------------------------- // Process the resources defined in App.xaml: if (appDotXamlResources != null) { try { foreach (XElement element in appDotXamlResources) { ResolvingReferencedXamlResources.ResolveAndMergeTheMergedDictionaries(element, appDotXamlFullPath, assemblyNameToProjectDictionary, new HashSet <string>(), resourcesCache); } } catch (Exception ex) { errorsIfAny = ex.Message; return(false); } } // Process the resources defined in the current file: try { ResolvingReferencedXamlResources.ResolveAndMergeTheMergedDictionaries(xdoc.Root, sourceXamlFileNameAndPath, assemblyNameToProjectDictionary, new HashSet <string>(), resourcesCache); } catch (Exception ex) { errorsIfAny = ex.Message; return(false); } //--------------------------------------- // Surround the document with a control in which we inject all the resources that we found in the end-user's "App.xaml" file: //--------------------------------------- if (appDotXamlResources != null && appDotXamlResources.Any()) { // Put those resouces in a control that will surround the xaml of the current page: var surroundingControlForResources = new XElement(DefaultXamlNamespace + "Border", xdoc.Root); surroundingControlForResources.Add(new XAttribute(XNamespace.Xmlns + "x", @"http://schemas.microsoft.com/winfx/2006/xaml")); // Note: This is required in case the XAML code contains the "x" prefix inside Markup Extensions (such as "{x:Null}"). It is not needed for the "x" prefix in elements and attributes (such as "x:Name"), because those are automatically imported when copying nodes, where as markup extensions are considered as simple strings by "Linq to XML". surroundingControlForResources.Add(new XAttribute("Tag", "AddedByDesignerToInjectAppDotXamlResources")); var resourcesContainer = new XElement(DefaultXamlNamespace + "Border.Resources"); surroundingControlForResources.AddFirst(resourcesContainer); resourcesContainer.Add(appDotXamlResources); // Replace the document with the one surrounded by the new control: xdoc = new XDocument(surroundingControlForResources); } #if Display_The_Processed_XAML // Uncomment to display the processed XAML: errorsIfAny = xdoc.Root.ToString(); outputXaml = xdoc.Root.ToString(); return(false); #endif //--------------------------------------- // Iterate through the document using a Stack<XElement> (pre-order traversal, no recursion) and process the nodes: //--------------------------------------- XElement root = xdoc.Root; Stack <System.Xml.Linq.XElement> stack = new Stack <System.Xml.Linq.XElement>(); stack.Push(root); while (stack.Count > 0) { System.Xml.Linq.XElement current = stack.Pop(); bool elementWasReplacedWithPlaceholder = false; // default value //--------------------------------------- // Process node to make it compatible with WPF (remove events such as PointerPressed, change "Page" to "UserControl", etc.): //--------------------------------------- ProcessNodeToMakeItCompatibleWithWpf.Process(current, ref warningsAndTips); //--------------------------------------- // Remove unknown nodes and attributes, and display "Cannot preview this element" instead: //--------------------------------------- // Verify that the node is not a property: if (!current.Name.LocalName.Contains(".")) { bool isKnownType = false; // Check to see if the element corresponds to a known type (only for elements that are supposed to be in the default namespace): Type type; if (current.Name.NamespaceName == DefaultXamlNamespace && TryGetType(current.Name, out type)) { isKnownType = true; // List all the event handlers of the type: List <string> eventHandlers = new List <string>(); foreach (EventInfo eventInfo in type.GetEvents()) { eventHandlers.Add(eventInfo.Name); } // Duplicate the list of attributes so that when we remove one, it doesn't affect the iteration: List <System.Xml.Linq.XAttribute> attributesListCopy = new List <System.Xml.Linq.XAttribute>(); foreach (System.Xml.Linq.XAttribute attr in current.Attributes()) { attributesListCopy.Add(attr); } // Remove event handlers: foreach (System.Xml.Linq.XAttribute attr in attributesListCopy) { // Check if the attribute is an event handler: //test+= " |||| " + attr.Name.LocalName + " " + attr.Name.NamespaceName + " " + (!attr.Name.LocalName.Contains(".")).ToString() + " " + eventHandlers.Contains(attr.Name.LocalName).ToString(); if (!attr.Name.LocalName.Contains(".") && eventHandlers.Contains(attr.Name.LocalName)) { // Remove the attrbute: attr.Remove(); } } } else if (current.Name.NamespaceName.EndsWith("assembly=mscorlib")) { isKnownType = true; } // If not known type, replace the element with a placeholder that says "Unable to display": if (!isKnownType) { // Create a border with inside a TextBlock that says "Unable to display": System.Xml.Linq.XElement msg = new System.Xml.Linq.XElement(DefaultXamlNamespace + "Border"); System.Xml.Linq.XElement msgTxt = new System.Xml.Linq.XElement(DefaultXamlNamespace + "TextBlock"); // Add the newly created stuff to the XAML: current.ReplaceWith(msg); msg.Add(msgTxt); // Set some attributes: msg.Add(new XAttribute("Background", "DarkRed")); msg.Add(new XAttribute("Opacity", "0.5")); msg.Add(new XAttribute("Tag", "AddedByDesignerAsPlaceholder")); msgTxt.Add(new XAttribute("Text", "Unable to preview this element")); msgTxt.Add(new XAttribute("TextWrapping", "Wrap")); msgTxt.Add(new XAttribute("TextAlignment", "Center")); msgTxt.Add(new XAttribute("HorizontalAlignment", "Stretch")); msgTxt.Add(new XAttribute("VerticalAlignment", "Center")); msgTxt.Add(new XAttribute("FontSize", "12")); msgTxt.Add(new XAttribute("Foreground", "#AAFFFFFF")); msgTxt.Add(new XAttribute("Tag", "AddedByDesignerForRendering")); // Give to that Border the same positioning information as the element that it replaces: MoveAttributeIfAny("Width", current, msg); MoveAttributeIfAny("Height", current, msg); MoveAttributeIfAny("HorizontalAlignment", current, msg); MoveAttributeIfAny("VerticalAlignment", current, msg); MoveAttributeIfAny("Margin", current, msg); MoveAttributeIfAny("Opacity", current, msg); MoveAttributeIfAny("MaxWidth", current, msg); MoveAttributeIfAny("MaxHeight", current, msg); MoveAttributeIfAny("MinWidth", current, msg); MoveAttributeIfAny("MinHeight", current, msg); MoveAttributeIfAny("Visibility", current, msg); MoveAttributeIfAny("Canvas.Left", current, msg); MoveAttributeIfAny("Canvas.Top", current, msg); MoveAttributeIfAny((XNamespace)"clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Toolkit" + "DockPanel.Dock", current, msg); MoveAttributeIfAny((XNamespace)"http://schemas.microsoft.com/winfx/2006/xaml" + "Name", current, msg); MoveAttributeIfAny((XNamespace)"http://schemas.microsoft.com/winfx/2006/xaml" + "Key", current, msg); // Remember that the element was replaced: elementWasReplacedWithPlaceholder = true; } } // Continue with the children of this element: if (!elementWasReplacedWithPlaceholder) { foreach (XElement element in current.Elements()) { stack.Push(element); } } } errorsIfAny = ""; //xdoc.ToString(); outputXaml = root.ToString(); return(true); }
private bool InterpolateDataToElement(XElement source, IScope datasource, out XElement result) { result = source; if (UseExtensions) { if (!MatchCondition(source, datasource, "if")) { return false; } #if !EMBEDQPT XmlIncludeProvider = XmlIncludeProvider ?? new XmlIncludeProvider(); #endif var globalreplace = source.Attr("xi-replace"); if (!string.IsNullOrWhiteSpace(globalreplace)) { _stringInterpolation.Interpolate(globalreplace); var xml = XmlIncludeProvider.GetXml(globalreplace, source, datasource); if (null == xml) { xml = XElement.Parse("<span class='no-ex replace'>no replace " + globalreplace + "</span>"); } result = xml; if (null != source.Parent) { source.ReplaceWith(xml); } source = xml; } if (source.Attr("xi-repeat").ToBool()) { XElement[] replace = ProcessRepeat(source, datasource); if (null == replace) { source.Remove(); } else { // ReSharper disable once CoVariantArrayConversion source.ReplaceWith(replace); } return false; } var include = source.Attr("xi-include"); if (!string.IsNullOrWhiteSpace(include)) { _stringInterpolation.Interpolate(include); var xml = XmlIncludeProvider.GetXml(include, source, datasource); if (null == xml) { xml = XElement.Parse("<span class='no-ex include'>no replace " + include + "</span>"); } source.ReplaceAll(xml); } } var processchild = true; if (!string.IsNullOrWhiteSpace(StopAttribute)) { var stopper = source.Attribute(StopAttribute); if (null != stopper) { if (stopper.Value != "0") { if (stopper.Value == "all") { return false; } processchild = false; } } } if (CodeOnly) { foreach (var a in source.Attributes()) { if (a.Name.LocalName == "code" || a.Name.LocalName == "id") { var val = a.Value; if (val.Contains(_stringInterpolation.AncorSymbol) && val.Contains(_stringInterpolation.StartSymbol)) { val = _stringInterpolation.Interpolate(val, datasource, SecondSource); a.Value = val; datasource.Set(a.Name.LocalName, val); } } } } else { var changed = true; while (changed) { changed = false; foreach (var a in source.Attributes().OrderBy(_ => { if (_.Value.Contains(AncorSymbol+"{") && _.Value.Contains("(")) { return 1000; } return 0; })) { var val = a.Value; if (val.Contains(_stringInterpolation.AncorSymbol) && val.Contains(_stringInterpolation.StartSymbol)) { val = _stringInterpolation.Interpolate(val, datasource, SecondSource); changed = changed || (val != a.Value); a.Value = val; datasource.Set(a.Name.LocalName, val); } } } changed = true; while (changed) { changed = false; foreach (var t in source.Nodes().OfType<XText>()) { var val = t.Value; if (val.Contains(_stringInterpolation.AncorSymbol) && val.Contains(_stringInterpolation.StartSymbol)) { val = _stringInterpolation.Interpolate(val, datasource, SecondSource); changed = changed || val != t.Value; t.Value = val; } } } } return processchild; }
private static void HandleSwitchElement(XElement element) { XElement defaultElement = element.Element(((XNamespace)LocalizationXmlConstants.XmlNamespace) + "default"); Verify.IsNotNull(defaultElement, "Missing element named 'default' at {0}", element); XElement newValueParent = defaultElement; CultureInfo currentCultureInfo = LocalizationScopeManager.CurrentLocalizationScope; foreach (XElement whenElement in element.Elements(((XNamespace)LocalizationXmlConstants.XmlNamespace) + "when")) { XAttribute cultureAttribute = whenElement.Attribute("culture"); Verify.IsNotNull(cultureAttribute, "Missing attriubte named 'culture' at {0}", whenElement); CultureInfo cultureInfo = new CultureInfo(cultureAttribute.Value); if (cultureInfo.Equals(currentCultureInfo)) { newValueParent = whenElement; break; } } element.ReplaceWith(newValueParent.Nodes()); }
private static void MergeIncludeFile(XElement inc) { var xdoc = LoadIncludeFile(inc); if (xdoc != null) { inc.ReplaceWith(xdoc.Root); } }
//=========================================================================================== private void ReplaceColorProfile(XElement annotation) { XElement restriction = new XElement(_Namespace + "restriction", new XAttribute("base", "xs:NMTOKEN")); foreach (string name in _GraphicsMagickNET.GetColorProfileNames()) { restriction.Add(new XElement(_Namespace + "enumeration", new XAttribute("value", name))); } annotation.ReplaceWith(CreateVarElement("ColorProfile", restriction)); }
//=========================================================================================== private void ReplaceColor(XElement annotation) { XElement restriction = new XElement(_Namespace + "restriction", new XAttribute("base", "xs:string")); if (_Depth >= QuantumDepth.Q8) { restriction.Add(new XElement(_Namespace + "pattern", new XAttribute("value", "#([0-9a-fA-F]{3,4})"))); restriction.Add(new XElement(_Namespace + "pattern", new XAttribute("value", "#([0-9a-fA-F]{2}){3,4}"))); } if (_Depth >= QuantumDepth.Q16) restriction.Add(new XElement(_Namespace + "pattern", new XAttribute("value", "#([0-9a-fA-F]{4}){3,4}"))); restriction.Add(new XElement(_Namespace + "pattern", new XAttribute("value", "Transparent"))); annotation.ReplaceWith(CreateVarElement("color", restriction)); }
private Dictionary<string, string> m_TranslKeysForPath; // ключ словаря - путь из файла idCsvFile, значение - соответствующий ключ перевода из text.csv private void translate(XElement tag, int language, string xmlFile, string idCsvFile, string textCsvFile) { var tagPath = getPath(tag); if (!m_TranslKeysForPath.ContainsKey(tagPath)) throw new Exception("в файле " + idCsvFile + " не найден путь " + tagPath + " существующего элемента <member> в файле " + xmlFile + ", невозможно идентифицировать перевод"); var translKey = m_TranslKeysForPath[tagPath]; var original = tag.ToString(); XElement[] tagChildren; var content = parseContent(tag, out tagChildren); if (!m_Translations.ContainsKey(translKey)) throw new Exception("в файле " + textCsvFile + " не найден перевод по ключу " + translKey); if (language < 1 || language > 2) throw new Exception("индекс языка отличный от 1 или 2 не поддерживается"); var translation = language == 1 ? m_Translations[translKey].Item1 : m_Translations[translKey].Item2; var encoded = HttpUtility.HtmlEncode(translation); // например, было содержимое "Свеча (X&0)", превращавшееся в XElement.Value в "Свеча (X&0)", в этом месте преобразуем обратно var newContent = ""; if (tagChildren.Count() != 0) try { newContent = string.Format(encoded, tagChildren); } catch (FormatException) { throw new Exception("Не удается сопоставить xml теги исходной строки формату перевода:\nисходная - " + original + "\nперевод - " + encoded); } else // встречаются странные строки без параметров, но с фигурными скобками newContent = encoded; var newText = "<" + tag.Name + ">" + newContent + "</" + tag.Name + ">"; var newEl = XElement.Parse(newText); newEl.Add(tag.Attributes()); tag.ReplaceWith(newEl); }
//=========================================================================================== private void ReplaceQuantum(XElement annotation) { string max; string baseType; switch (_Depth) { case QuantumDepth.Q8: max = "255"; baseType = "xs:unsignedByte"; break; case QuantumDepth.Q16: max = "65535"; baseType = "xs:unsignedShort"; break; default: throw new NotImplementedException(); } annotation.ReplaceWith( CreateVarElement("quantum", new XElement(_Namespace + "restriction", new XAttribute("base", baseType), new XElement(_Namespace + "minInclusive", new XAttribute("value", "0")), new XElement(_Namespace + "maxInclusive", new XAttribute("value", max))))); }
/// <summary> /// Given a xml node and its decendents that should be folded, the method updates /// the node accordingly. /// </summary> /// <param name="parent"></param> /// <param name="isFolding"></param> private void FoldingXml(XElement parent, Predicate<XElement> isFolding) { var children = GetChildrenXElements(parent); children.Reverse(); foreach (var child in children) { FoldingXml(child, isFolding); } if (isFolding.Invoke(parent)) parent.ReplaceWith(CreateEntirelyFoldedElement(parent)); }
private void EditItem(Entry entry, XElement element) { element.ReplaceWith(XSerializer.ToXElement(entry)); }