public override void Process() { base.Process(); var element = TextTag.TagNode; var text = DataReader.ReadText(TextTag.Expression); XElement parent = element.Parent; if (parent.Name == WordMl.TableRowName) { parent = element.Element(WordMl.SdtContentName).Element(WordMl.TableCellName); } var textElement = DocxHelper.CreateTextElement(element, parent, text); var result = this.CreateDynamicContentTags ? DocxHelper.CreateDynamicContentElement(new[] { textElement }, this.TextTag.TagNode, this.DynamicContentLockingType) : textElement; if (element.Parent.Name != WordMl.TableRowName) { element.AddBeforeSelf(result); } else { var cell = new XElement(WordMl.TableCellName, result); cell.AddFirst(element.Descendants(WordMl.TableCellPropertiesName)); element.AddBeforeSelf(cell); } element.Remove(); }
private static XElement CompileWithBSharp(XElement result) { var compileroptions = new BSharpConfig { UseInterpolation = true, SingleSource = true }; var compileresult = BSharpCompiler.Compile(new[] { result }, compileroptions); var newresult = new XElement("bsharp"); foreach (var w in compileresult.Get(BSharpContextDataType.Working)) { var copy = new XElement(w.Compiled); if (null != w.Error) { copy.AddFirst(new XElement("error", new XText(w.Error.ToString()))); } newresult.Add(copy); } var e = new XElement("errors"); foreach (var er in compileresult.GetErrors()) { e.Add(XElement.Parse(new XmlSerializer().Serialize("error", er)).Element("error")); } if (e.HasElements) { newresult.Add(e); } result = newresult; return result; }
public void Execute(JobExecutionContext context) { try { log.Info("AllListJob开始更新"); var videos = ListCache.Instance.Items[new VideoNodeKey(null, 0, null)].Ver1; var root = new XElement("vlist"); int num = 0; foreach (var video in videos) { root.Add(ResponseUtils.ResponseBack(ListCache.Instance.Dictionary[video])); num++; } root.AddFirst(new XElement("count", num)); ResponseUtils.SaveXml("all.xml", root); YesterdayListCache.Instance.Refresh(videos); SerizlizerUtils<YesterdayVideoNode>.SerializeSplitCache(YesterdayListCache.Instance.Items, _buffername); //SerizlizerUtils<VideoNode>.SerializeSplitCache(videos, _buffername); } catch (Exception ex) { log.Error(ex); } finally { log.Info("AllListJob结束更新"); } }
private void AddContentTypeMetadata(XElement head) { var meta = new XElement("meta"); meta.SetAttributeValue("http-equiv", "content-type"); meta.SetAttributeValue("content", "text/html; charset=UTF-8"); head.AddFirst(meta); }
private static OrderInfo CreateOrder(string countryCode) { var order = new OrderInfo(); var xElement = new XElement(CustomerDatatypes.Customer.ToString()); xElement.AddFirst(new XElement("customerCountry", new XCData(""))); order.CustomerInfo.customerInformation = new XDocument(xElement); order.CustomerCountry = countryCode; return order; }
/// <summary> /// Writes the variables as xml /// </summary> protected void WriteVariables(XElement varXML) { VariableXMLWriter varWriter = new VariableXMLWriter(); foreach(Variable v in this.Model){ varWriter.ToWrite = v; varXML.AddFirst(varWriter.Write()); } }
public static void Reparent(this IEnumerable<XElement> nodes, XElement parent, bool first = false) { var list = nodes.ToArray(); list.Remove(); if (first) parent.AddFirst(list); else parent.Add(list); }
static void AddElementToXml(DirectoryInfo rootDir, FileInfo[] files) { XElement nextDir = new XElement("dir"); nextDir.Add(new XAttribute("name", rootDir.FullName)); root.AddFirst(nextDir); foreach (FileInfo file in files) { XElement nextFile = new XElement("file"); nextFile.Add(new XAttribute("name", file.Name)); nextDir.AddFirst(nextFile); } }
public static XDocument CreateHelpPage(Uri baseUri, IEnumerable<OperationHelpInformation> operations) { XDocument document = CreateBaseDocument(SR2.GetString(SR2.HelpPageOperationsAt, baseUri)); XElement table = new XElement(HtmlTableElementName, new XElement(HtmlTrElementName, new XElement(HtmlThElementName, SR2.GetString(SR2.HelpPageUri)), new XElement(HtmlThElementName, SR2.GetString(SR2.HelpPageMethod)), new XElement(HtmlThElementName, SR2.GetString(SR2.HelpPageDescription)))); string lastOperation = null; XElement firstTr = null; int rowspan = 0; foreach (OperationHelpInformation operationHelpInfo in operations.OrderBy(o => FilterQueryVariables(o.UriTemplate))) { string operationUri = FilterQueryVariables(operationHelpInfo.UriTemplate); string description = operationHelpInfo.Description; if (String.IsNullOrEmpty(description)) { description = SR2.GetString(SR2.HelpPageDefaultDescription, BuildFullUriTemplate(baseUri, operationHelpInfo.UriTemplate)); } XElement tr = new XElement(HtmlTrElementName, new XElement(HtmlTdElementName, new XAttribute(HtmlTitleAttributeName, BuildFullUriTemplate(baseUri, operationHelpInfo.UriTemplate)), new XElement(HtmlAElementName, new XAttribute(HtmlRelAttributeName, HtmlOperationClass), new XAttribute(HtmlHrefAttributeName, String.Format(CultureInfo.InvariantCulture, HelpOperationPageUrl, operationHelpInfo.Name)), operationHelpInfo.Method)), new XElement(HtmlTdElementName, description)); table.Add(tr); if (operationUri != lastOperation) { XElement td = new XElement(HtmlTdElementName, operationUri == lastOperation ? String.Empty : operationUri); tr.AddFirst(td); if (firstTr != null && rowspan > 1) { firstTr.Descendants(HtmlTdElementName).First().Add(new XAttribute(HtmlRowspanAttributeName, rowspan)); } firstTr = tr; rowspan = 0; lastOperation = operationUri; } ++rowspan; } if (firstTr != null && rowspan > 1) { firstTr.Descendants(HtmlTdElementName).First().Add(new XAttribute(HtmlRowspanAttributeName, rowspan)); } document.Descendants(HtmlBodyElementName).First().Add(new XElement(HtmlDivElementName, new XAttribute(HtmlIdAttributeName, HtmlContentClass), new XElement(HtmlPElementName, new XAttribute(HtmlClassAttributeName, HtmlHeading1Class), SR2.GetString(SR2.HelpPageOperationsAt, baseUri)), new XElement(HtmlPElementName, SR2.GetString(SR2.HelpPageStaticText)), table)); return document; }
/// <summary> /// Ensures that a named element is the first child. /// </summary> /// <param name="this">This parent element.</param> /// <param name="name">The element's name that must be the first one.</param> /// <returns>The first element that may have been moved or inserted.</returns> public static XElement EnsureFirstElement(this XElement @this, XName name) { XElement e = @this.Element(name); if (e != null) { e.Remove(); } else { e = new XElement(name); } @this.AddFirst(e); return(e); }
/// <summary> /// Tests the Parent property on Node. /// </summary> /// <param name="context"></param> /// <returns></returns> //[Variation(Desc = "NodeParent")] public void NodeParent() { // Only elements are returned as parents from the Parent property. // Documents are not returned. XDocument document = new XDocument(); XNode[] nodes = new XNode[] { new XComment("comment"), new XElement("element"), new XProcessingInstruction("target", "data"), new XDocumentType("name", "publicid", "systemid", "internalsubset") }; foreach (XNode node in nodes) { Validate.IsNull(node.Parent); document.Add(node); Validate.IsReferenceEqual(document, node.Document); // Parent element is null. Validate.IsNull(node.Parent); document.RemoveNodes(); } // Now test the cases where an element is the parent. nodes = new XNode[] { new XComment("abcd"), new XElement("nested"), new XProcessingInstruction("target2", "data2"), new XText("text") }; XElement root = new XElement("root"); document.ReplaceNodes(root); foreach (XNode node in nodes) { Validate.IsNull(node.Parent); root.AddFirst(node); Validate.IsReferenceEqual(node.Parent, root); root.RemoveNodes(); Validate.IsNull(node.Parent); } }
/// <summary> /// Convert MyDistanceNode's inputs from A,B to Input 1, Input 2 (required after the node was put into Transforms) /// Author: MP /// </summary> public static string Convert11To12(string xml) { XDocument document = XDocument.Parse(xml); foreach (XElement node in document.Root.Descendants("MyDistanceNode")) { XElement IO = new XElement("IO"); XElement InputBranches = new XElement("InputBranches"); InputBranches.Value = "2"; IO.AddFirst(InputBranches); node.AddFirst(IO); } return document.ToString(); }
public string AllList(UpdateFilter filter) { try { var videos = ListCache.Instance.Items[new VideoNodeKey(null, 0, null)].Ver1; var xml = new XElement("vlist"); var count = videos.BackPageList(filter.c,filter.s,xml); xml.AddFirst(new XElement("count", count), new XElement("page_count", PageUtils.PageCount(count, filter.c)) ); return xml.ToString(SaveOptions.DisableFormatting); } catch (Exception ex) { return BoxUtils.FormatErrorMsg(ex); } }
public string TagSearchSmart(TagSearchFilter filter) { try { var xml = new XElement("taglist"); var count = LuceneNetUtil.TagSearch(filter, EpgIndexNode.NameField, Searcher.SegmentKeyWord(filter.k), xml); xml.AddFirst(new XElement("count", count), new XElement("page_count", PageUtils.PageCount(count, filter.c))); return xml.ToString(SaveOptions.DisableFormatting); } catch (KeyNotFoundException) { return NoPlatForm(); } catch (Exception ex) { return BoxUtils.FormatErrorMsg(ex); } }
public XElement ToXmlElement() { try { var elem = new XElement(XName.Get("pattern")); elem.SetAttributeValue(XName.Get("name"), Name); foreach (var patternHeader in Headers) { var header = new XElement(XName.Get("header")); header.SetAttributeValue(XName.Get("name"), patternHeader.Name); header.SetAttributeValue(XName.Get("value"), patternHeader.Value); elem.AddFirst(header); } if (Contexts.Count != 0) { var contexts = new XElement(XName.Get("contexts")); foreach (var celem in Contexts.Select(context => context.ToXmlElement())) { contexts.AddFirst(celem); } } foreach (var patternText in Texts) { var text = new XElement(XName.Get("text")); text.SetAttributeValue(XName.Get("type"), patternText.Encoding); text.Value = patternText.Text; } return elem; } catch (Exception e) { throw new PatternXmlException("Ошибка трансформации паттерна в xml формат. Подробнее в InnerException", e); } }
public virtual XElement GenerateSiteElement(PageData pageData, string url) { var property = pageData.Property[PropertySEOSitemaps.PropertyName] as PropertySEOSitemaps; var element = new XElement( SitemapXmlNamespace + "url", new XElement(SitemapXmlNamespace + "loc", url), new XElement(SitemapXmlNamespace + "lastmod", pageData.Saved.ToString(DateTimeFormat)), new XElement(SitemapXmlNamespace + "changefreq", (property != null) ? property.ChangeFreq : "weekly"), new XElement(SitemapXmlNamespace + "priority", (property != null) ? property.Priority : GetPriority(url))); if (IsDebugMode) { element.AddFirst(new XComment( string.Format( "page ID: '{0}', name: '{1}', language: '{2}'", pageData.PageLink.ID, pageData.PageName, pageData.LanguageBranch))); } return element; }
public override void InsertImport(XElement target) { var code = "import CoverageWriter"; var ast = Python3CodeToXml.Instance.Generate(code); target.AddFirst(ast); }
internal override XElement ToXML(string featureNS) { string wfs = "http://www.opengis.net/wfs"; string ogc = "http://www.opengis.net/ogc"; string localTypeName = string.Empty; XElement delete = new XElement("{" + wfs + "}Delete"); #region 必设属性的判断 if (string.IsNullOrEmpty(this.TypeName)) { return delete; } #endregion //获取TypeName的本地名称。 string[] splitNames = this.TypeName.Split(':'); if (splitNames != null) { int totalCount = splitNames.Length; localTypeName = splitNames[totalCount - 1]; } if (string.IsNullOrEmpty(localTypeName)) { return delete; } delete.SetAttributeValue(XName.Get("typeName"), localTypeName); XElement filter = new XElement(XName.Get("{" + ogc + "}Filter")); if (FeatureIDs != null && FeatureIDs.Length > 0) { for (int i = 0; i < FeatureIDs.Length; i++) { XElement featureID = new XElement(XName.Get("{" + ogc + "}FeatureId"), new XAttribute(XName.Get("fid"), FeatureIDs[i])); filter.Add(featureID); } } else if (this.Filter != null) { XElement subFilterValue = this.Filter.ToXML(); if (subFilterValue != null) { filter.Add(subFilterValue); } } else { //啥也不干 } delete.AddFirst(filter); return delete; }
// <?xml version="1.0"?> // <?order alpha ascending?> // <art xmlns='urn:art-org:art'> // <period name='Renaissance' xmlns:a='urn:art-org:artists'> // <a:artist>Leonardo da Vinci</a:artist> // <a:artist>Michelangelo</a:artist> // <a:artist><![CDATA[Donatello]]></a:artist> // </period> // <!-- 在此处插入 period --> // </art> public static XDocument CreateDocumentVerbose() { XNamespace nsArt = "urn:art-org:art"; XNamespace nsArtists = "urn:art-org:artists"; // 创建文档 XDocument document = new XDocument(); // 创建 xml 声明,并在 // 文档中对其进行设置 document.Declaration = new XDeclaration("1.0", null, null); // 创建 art 元素,并将其 // 添加到文档中 XElement art = new XElement(nsArt + "art"); document.Add(art); // 创建顺序处理指令,并将其 // 添加到 art 元素之前 XProcessingInstruction pi = new XProcessingInstruction("order", "alpha ascending"); art.AddBeforeSelf(pi); // 创建 period 元素,并将其 // 添加到 art 元素中 XElement period = new XElement(nsArt + "period"); art.Add(period); // 向 period 元素中添加 name 特性 period.SetAttributeValue("name", "Renaissance"); // 创建命名空间声明 xmlns:a,并将其 // 添加到 period 元素中 XAttribute nsdecl = new XAttribute(XNamespace.Xmlns + "a", nsArtists); period.Add(nsdecl); // 创建 artist 元素和 // 基础文本节点 period.SetElementValue(nsArtists + "artist", "Michelangelo"); XElement artist = new XElement(nsArtists + "artist", "Leonardo ", "da ", "Vinci"); period.AddFirst(artist); artist = new XElement(nsArtists + "artist"); period.Add(artist); XText cdata = new XText("Donatello"); artist.Add(cdata); // 创建注释,并将其 // 添加到 art 元素中 XComment comment = new XComment("insert period here"); art.Add(comment); return document; }
public void NodeAllContentBeforeSelf() { XElement parent = new XElement("parent"); XComment child = new XComment("Self is a comment"); XComment comment1 = new XComment("Another comment"); XComment comment2 = new XComment("Yet another comment"); XElement element1 = new XElement("childelement", new XElement("nested"), new XAttribute("foo", "bar")); XElement element2 = new XElement("childelement2", new XElement("nested"), new XAttribute("foo", "bar")); XAttribute attribute = new XAttribute("attribute", "value"); // If no parent, should not be any content before it. Assert.Empty(child.NodesBeforeSelf()); // Add child to parent. Should still be no content before it. // Attributes are not content. parent.Add(attribute); parent.Add(child); Assert.Empty(child.NodesBeforeSelf()); // Add more children and validate. parent.Add(comment1); parent.Add(element1); Assert.Empty(child.NodesBeforeSelf()); parent.AddFirst(element2); parent.AddFirst(comment2); Assert.Equal(new XNode[] { comment2, element2 }, child.NodesBeforeSelf()); }
private static void InitEmptyHeaderOrFooter(MainDocumentPart mainDocPart, XElement sect, XName referenceXName, string toType) { XDocument xDoc = null; if (referenceXName == W.headerReference) { xDoc = XDocument.Parse( @"<?xml version='1.0' encoding='utf-8' standalone='yes'?> <w:hdr xmlns:wpc='http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas' xmlns:mc='http://schemas.openxmlformats.org/markup-compatibility/2006' xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:r='http://schemas.openxmlformats.org/officeDocument/2006/relationships' xmlns:m='http://schemas.openxmlformats.org/officeDocument/2006/math' xmlns:v='urn:schemas-microsoft-com:vml' xmlns:wp14='http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing' xmlns:wp='http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing' xmlns:w10='urn:schemas-microsoft-com:office:word' xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main' xmlns:w14='http://schemas.microsoft.com/office/word/2010/wordml' xmlns:w15='http://schemas.microsoft.com/office/word/2012/wordml' xmlns:wpg='http://schemas.microsoft.com/office/word/2010/wordprocessingGroup' xmlns:wpi='http://schemas.microsoft.com/office/word/2010/wordprocessingInk' xmlns:wne='http://schemas.microsoft.com/office/word/2006/wordml' xmlns:wps='http://schemas.microsoft.com/office/word/2010/wordprocessingShape' mc:Ignorable='w14 w15 wp14'> <w:p> <w:pPr> <w:pStyle w:val='Header' /> </w:pPr> <w:r> <w:t></w:t> </w:r> </w:p> </w:hdr>"); var newHeaderPart = mainDocPart.AddNewPart<HeaderPart>(); newHeaderPart.PutXDocument(xDoc); var referenceToAdd = new XElement(W.headerReference, new XAttribute(W.type, toType), new XAttribute(R.id, mainDocPart.GetIdOfPart(newHeaderPart))); sect.AddFirst(referenceToAdd); } else { xDoc = XDocument.Parse(@"<?xml version='1.0' encoding='utf-8' standalone='yes'?> <w:ftr xmlns:wpc='http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas' xmlns:mc='http://schemas.openxmlformats.org/markup-compatibility/2006' xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:r='http://schemas.openxmlformats.org/officeDocument/2006/relationships' xmlns:m='http://schemas.openxmlformats.org/officeDocument/2006/math' xmlns:v='urn:schemas-microsoft-com:vml' xmlns:wp14='http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing' xmlns:wp='http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing' xmlns:w10='urn:schemas-microsoft-com:office:word' xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main' xmlns:w14='http://schemas.microsoft.com/office/word/2010/wordml' xmlns:w15='http://schemas.microsoft.com/office/word/2012/wordml' xmlns:wpg='http://schemas.microsoft.com/office/word/2010/wordprocessingGroup' xmlns:wpi='http://schemas.microsoft.com/office/word/2010/wordprocessingInk' xmlns:wne='http://schemas.microsoft.com/office/word/2006/wordml' xmlns:wps='http://schemas.microsoft.com/office/word/2010/wordprocessingShape' mc:Ignorable='w14 w15 wp14'> <w:p> <w:pPr> <w:pStyle w:val='Footer' /> </w:pPr> <w:r> <w:t></w:t> </w:r> </w:p> </w:ftr>"); var newFooterPart = mainDocPart.AddNewPart<FooterPart>(); newFooterPart.PutXDocument(xDoc); var referenceToAdd = new XElement(W.footerReference, new XAttribute(W.type, toType), new XAttribute(R.id, mainDocPart.GetIdOfPart(newFooterPart))); sect.AddFirst(referenceToAdd); } }
private static void AddReferenceToExistingHeaderOrFooter(MainDocumentPart mainDocPart, XElement sect, string rId, XName reference, string toType) { if (reference == W.headerReference) { var referenceToAdd = new XElement(W.headerReference, new XAttribute(W.type, toType), new XAttribute(R.id, rId)); sect.AddFirst(referenceToAdd); } else { var referenceToAdd = new XElement(W.footerReference, new XAttribute(W.type, toType), new XAttribute(R.id, rId)); sect.AddFirst(referenceToAdd); } }
/// <summary> /// Tests the AddFirst methods on Container. /// </summary> /// <param name="context"></param> /// <returns></returns> //[Variation(Desc = "ContainerAddFirst")] public void ContainerAddFirst() { XElement element = new XElement("foo"); // Adding null does nothing. element.AddFirst(null); Validate.Count(element.Nodes(), 0); // Add a sentinal value. XText text = new XText("abcd"); element.AddFirst(text); // Add node and string. XComment comment = new XComment("this is a comment"); string str = "this is a string"; element.AddFirst(comment); element.AddFirst(str); Validate.EnumeratorDeepEquals(element.Nodes(), new XNode[] { new XText(str), comment, text }); element.RemoveAll(); Validate.Count(element.Nodes(), 0); // Now test params overload. element.AddFirst(text); element.AddFirst(comment, str); Validate.EnumeratorDeepEquals(element.Nodes(), new XNode[] { comment, new XText(str), text }); // Can't use to add attributes. XAttribute a = new XAttribute("foo", "bar"); try { element.AddFirst(a); Validate.ExpectedThrow(typeof(ArgumentException)); } catch (Exception ex) { Validate.Catch(ex, typeof(ArgumentException)); } }
private void AddNodeDocumentation(XElement element, String documentation) { if (String.IsNullOrEmpty(documentation)) return; element.Descendants("{http://schemas.microsoft.com/ado/2008/09/edm}Documentation").Remove(); element.AddFirst(new XElement("{http://schemas.microsoft.com/ado/2008/09/edm}Documentation", new XElement("{http://schemas.microsoft.com/ado/2008/09/edm}Summary", documentation))); }
/// <summary> /// 分页输出 /// </summary> private static string CreatePageList(IEnumerable<int> list, ListFilter filter, VideoPars pars, bool isEx) { if (filter.order != "s") list = VideoSortUtils<VideoNode>.Sort(list, filter); var xml = new XElement("vlist"); xml.Add(new XElement("countInPage", filter.c), new XElement("page", filter.s)); var count = list.PageList(filter, pars, xml, isEx); xml.AddFirst(new XElement("count", count), new XElement("page_count", PageUtils.PageCount(count, filter.c))); return xml.ToString(SaveOptions.DisableFormatting); }
private XDocument GenerateFeed(IEnumerable<Notez> notes, string title, string noteTitle, Func<Notez, string> html) { XElement outputFeed = new XElement(atom + "feed"); XDocument xml = new XDocument(outputFeed); outputFeed.AddFirst( new XElement(atom + "title", title), new XElement(atom + "subtitle", "Why don't you leave a happy note for someone?"), new XElement(atom + "link", new XAttribute("href", "http://happynotez.org/")) ); bool first = true; foreach (Notez note in notes) { if (first) { outputFeed.Add(new XElement(atom + "updated", note.Timestamp.ToString(atomUpdatedFormat))); first = false; } outputFeed.Add( new XElement(atom + "entry", new XElement(atom + "title", noteTitle), new XElement(atom + "id", note.ID), new XElement(atom + "updated", note.Timestamp.ToString(atomUpdatedFormat)), new XElement(atom + "link", new XAttribute("href", "http://happynotez.org/" + note.ID)), new XElement(atom + "content", new XAttribute("type", "html"), html(note)) )); } return xml; }
/// <summary> /// Tests the AllContentAfterSelf method on Node. /// </summary> /// <param name="context"></param> /// <returns></returns> //[Variation(Desc = "NodeAllContentAfterSelf")] public void NodeAllContentAfterSelf() { XElement parent = new XElement("parent"); XComment child = new XComment("Self is a comment"); XComment comment1 = new XComment("Another comment"); XComment comment2 = new XComment("Yet another comment"); XElement element1 = new XElement("childelement", new XElement("nested"), new XAttribute("foo", "bar")); XElement element2 = new XElement("childelement2", new XElement("nested"), new XAttribute("foo", "bar")); XAttribute attribute = new XAttribute("attribute", "value"); // If no parent, should not be any content after it. Validate.Enumerator<XNode>(child.NodesAfterSelf(), new XNode[0]); // Add child to parent. Should still be no content after it. // Attributes are not content. parent.Add(child); parent.Add(attribute); Validate.Enumerator<XNode>(child.NodesAfterSelf(), new XNode[0]); // Add more children and validate. parent.AddFirst(comment1); parent.AddFirst(element1); Validate.Enumerator<XNode>(child.NodesAfterSelf(), new XNode[0]); parent.Add(element2); parent.Add(comment2); Validate.Enumerator<XNode>(child.NodesAfterSelf(), new XNode[] { element2, comment2 }); }
//[Variation(Priority = 1, Desc = "XElement - Working on the text nodes 2.")] public void WorkOnTextNodes2() { XElement elem = new XElement("A", "text2"); elem.AddFirst("text0"); elem.AddFirst("text1"); using (UndoManager undo = new UndoManager(elem)) { undo.Group(); using (EventsHelper eHelper = new EventsHelper(elem)) { elem.FirstNode.Remove(); eHelper.Verify(XObjectChange.Remove); TestLog.Compare(!elem.IsEmpty, "Did not remove correctly"); elem.FirstNode.Remove(); eHelper.Verify(XObjectChange.Remove); TestLog.Compare(!elem.IsEmpty, "Did not remove correctly"); elem.FirstNode.Remove(); eHelper.Verify(XObjectChange.Remove); TestLog.Compare(elem.IsEmpty, "Did not remove correctly"); } undo.Undo(); TestLog.Compare(elem.Value, "text1text0text2", "Undo did not work"); } }
protected void Page_Load(object sender, EventArgs e) { string[] filePaths; string[] fileNames; lblError.ForeColor = System.Drawing.Color.Red; try { filePaths = Directory.GetFiles(Server.MapPath("~") + "datafiles", "*.xml"); fileNames = filePaths; } catch (Exception error) { lblError.Text = "Oh on! Error: " + error.Message; filePaths = new string[0]; fileNames = new string[0]; } if (IsPostBack) { if (drpChannels.SelectedIndex < 0 || txtHeadline.Text == "" || txtHeadline.Text.Length > 50 || txtDescription.Text == "" || txtDescription.Text.Length > 85) { lblError.Text = "There Are Errors In Your Article!"; if (drpChannels.SelectedIndex < 0) { lblChannelError.Text = "A channel needs to be selected!"; } else { lblChannelError.Text = ""; } if (txtHeadline.Text == "") { lblTitleError.Text = "The headline is required!"; } else if (txtHeadline.Text.Length > 50) { lblTitleError.Text = "The headline is too long!"; } else { lblTitleError.Text = ""; } if (txtDescription.Text == "") { lblDescriptionError.Text = "The description is required!"; } else if (txtDescription.Text.Length > 100) { lblDescriptionError.Text = "The Description is too long!"; } else { lblDescriptionError.Text = ""; } drpChannels.SelectedIndex = drpChannels.SelectedIndex; } else { lblError.Text = ""; lblChannelError.Text = ""; lblTitleError.Text = ""; lblDescriptionError.Text = ""; try { // Get post data for request object NameValueCollection nvc = Request.Form; string strHeadline = ""; string strDesc = ""; // Fill string with post data if (!string.IsNullOrEmpty(nvc["txtHeadline"])) { strHeadline += nvc["txtHeadline"]; } if (!string.IsNullOrEmpty(nvc["txtDescription"])) { strDesc += nvc["txtDescription"]; } /*// Put data into article format string strArticle = "<?xml version = \"1.0\" encoding = \"UTF-8\" standalone = \"no\"?>\n\n<rss version=\"2.0\">\n\t<channel>\n\t\t<item>\n\t\t\t<title>" + strHeadline + "</title>\n\t\t\t<link></link>\n\t\t\t<description><![CDATA[" + strDesc + "]]></description>\n\t\t</item>\n\t</channel>\n</rss>"; string strTitle = + DateTime.Today.Month + "-" + DateTime.Today.Day + "-" + DateTime.Today.Year + "H" + DateTime.Now.Hour + "M" + DateTime.Now.Minute + "S" + DateTime.Now.Second + ".xml"; // Make path with today's date as name string path = @"C:\Users\Student3\Desktop\NewsWriter\datafiles\"+strTitle; // Make new file and write to it System.IO.File.WriteAllText(path, strArticle);*/ // Open channel XDocument feed = XDocument.Load(filePaths[drpChannels.SelectedIndex]); // Create Elements XElement desc = new XElement("description", new XCData(strDesc)); XElement link = new XElement("link", ""); XElement title = new XElement("title", new XCData(strHeadline)); XElement item = new XElement("item", ""); XElement pubDate = new XElement("pubDate", DateTime.Today.Month.ToString() +"/"+DateTime.Today.Day.ToString()+"/"+DateTime.Today.Year.ToString()); // Place Elements item.AddFirst(desc); item.AddFirst(pubDate); item.AddFirst(link); item.AddFirst(title); feed.Element("rss").Element("channel").Element("description").AddAfterSelf(item); // Save Channel feed.Save(filePaths[drpChannels.SelectedIndex]); // Inform user of success lblError.Text = "Congrats! You made a new article!"; lblError.ForeColor = System.Drawing.Color.Lime; txtHeadline.Text = ""; txtDescription.Text = ""; } catch (Exception error) { lblError.Text = "Oh No!<br />Error: " + error.Message; } } } for (int i = 0; i < fileNames.Length; i++) { fileNames[i] = Path.GetFileNameWithoutExtension(fileNames[i]); } drpChannels.DataSource = fileNames; drpChannels.DataBind(); }
private static void ReplaceBrushesInDrawingGroups(XElement rootElement, string xamlName) { //three steps of colouring: 1. global Color, 2, global ColorBrush, 3. local ColorBrush //<Color x:Key="ImagesColor1">#FF000000</Color> //<SolidColorBrush x:Key="ImagesColorBrush1" Color="{DynamicResource ImagesColor1}" /> //<SolidColorBrush x:Key="JOG_BrushColor1" Color="{Binding Color, Source={StaticResource ImagesColorBrush1}}" /> var firstChar = Char.ToUpper(xamlName[0]); xamlName = firstChar + xamlName.Remove(0, 1); var allBrushes = CollectBrushAttributesWithColor(rootElement) .Select(a => a.Value) .Distinct(StringComparer.InvariantCultureIgnoreCase) //same Color only once .Select((s, i) => new { ResKey1 = string.Format("{0}Color{1}", xamlName, i + 1), ResKey2 = string.Format("{0}ColorBrush{1}", xamlName, i + 1), Color = s }) //add numbers .ToList(); //building Elements like: <SolidColorBrush x:Key="ImagesColorBrush1" Color="{DynamicResource ImagesColor1}" /> rootElement.AddFirst(allBrushes .Select(brush => new XElement(nsDef + "SolidColorBrush", new XAttribute(nsx + "Key", brush.ResKey2), new XAttribute("Color", string.Format("{{DynamicResource {0}}}", brush.ResKey1))))); //building Elements like: <Color x:Key="ImagesColor1">#FF000000</Color> rootElement.AddFirst(allBrushes .Select(brush => new XElement(nsDef + "Color", new XAttribute(nsx + "Key", brush.ResKey1), brush.Color))); var colorKeys = allBrushes.ToDictionary(brush => brush.Color, brush => brush.ResKey2); var drawingGroups = rootElement.Elements(nsDef + "DrawingGroup").ToList(); foreach (var node in drawingGroups) { //get Name of DrawingGroup var nameDg = node.Attribute(nsx + "Key").Value; var nameBrushBase = nameDg.Replace("DrawingGroup", "Brush"); var brushAttributes = CollectBrushAttributesWithColor(node).ToList(); foreach (var brushAttribute in brushAttributes) { var color = brushAttribute.Value; string resKey; if (colorKeys.TryGetValue(color, out resKey)) { //global color found //build resourcename var localName = brushAttributes.Count > 1 ? string.Format("{0}Color{1}", nameBrushBase, brushAttributes.IndexOf(brushAttribute) + 1) : string.Format("{0}Color", nameBrushBase); //dont add number if only one color node.AddBeforeSelf(new XElement(nsDef + "SolidColorBrush", new XAttribute(nsx + "Key", localName), new XAttribute("Color", string.Format("{{Binding Color, Source={{StaticResource {0}}}}}", resKey)) )); brushAttribute.Value = "{DynamicResource " + localName + "}"; } } } }
protected virtual XElement GenerateSiteElement(IContent contentData, string url) { DateTime modified = DateTime.Now.AddMonths(-1); var changeTrackableContent = contentData as IChangeTrackable; var versionableContent = contentData as IVersionable; if (changeTrackableContent != null) { modified = changeTrackableContent.Saved; } else if (versionableContent != null && versionableContent.StartPublish.HasValue) { modified = versionableContent.StartPublish.Value; } var property = contentData.Property[PropertySEOSitemaps.PropertyName] as PropertySEOSitemaps; var element = new XElement( SitemapXmlNamespace + "url", new XElement(SitemapXmlNamespace + "loc", url), new XElement(SitemapXmlNamespace + "lastmod", modified.ToString(DateTimeFormat)), new XElement(SitemapXmlNamespace + "changefreq", (property != null) ? property.ChangeFreq : "weekly"), new XElement(SitemapXmlNamespace + "priority", (property != null) ? property.Priority : GetPriority(url)) ); if (SitemapSettings.Instance.EnableHrefLang) { AddHrefLangToElement(contentData, element); } if (IsDebugMode) { var localeContent = contentData as ILocale; var language = localeContent != null ? localeContent.Language : CultureInfo.InvariantCulture; element.AddFirst(new XComment(string.Format("page ID: '{0}', name: '{1}', language: '{2}'", contentData.ContentLink.ID, contentData.Name, language.Name))); } return element; }