//[Variation(Priority = 1, Desc = "Open on node type: XElement (root)", Params = new object[] { XmlNodeType.Element, 0, new string[] { "A", "", "" }, 15 })] //[Variation(Priority = 0, Desc = "Open on node type: XElement (in the mIddle)", Params = new object[] { XmlNodeType.Element, 1, new string[] { "B", "", "x" }, 11 })] //[Variation(Priority = 0, Desc = "Open on node type: XElement (leaf I.)", Params = new object[] { XmlNodeType.Element, 3, new string[] { "D", "", "y" }, 2 })] //[Variation(Priority = 1, Desc = "Open on node type: XElement (leaf II.)", Params = new object[] { XmlNodeType.Element, 4, new string[] { "E", "p", "nsp" }, 1 })] //[Variation(Priority = 2, Desc = "Open on node type: PI (root level)", Params = new object[] { XmlNodeType.ProcessingInstruction, 0, new string[] { "PI", "" }, 1 })] //[Variation(Priority = 2, Desc = "Open on node type: PI", Params = new object[] { XmlNodeType.ProcessingInstruction, 1, new string[] { "PIX", "click" }, 1 })] //[Variation(Priority = 2, Desc = "Open on node type: Comment (root level)", Params = new object[] { XmlNodeType.Comment, 0, new string[] { "comment1" }, 1 })] //[Variation(Priority = 2, Desc = "Open on node type: Comment", Params = new object[] { XmlNodeType.Comment, 1, new string[] { "comm2" }, 1 })] //[Variation(Priority = 0, Desc = "Open on node type: Text (root level)", Params = new object[] { XmlNodeType.Text, 0, new string[] { "\t" }, 1 })] //[Variation(Priority = 1, Desc = "Open on node type: Text", Params = new object[] { XmlNodeType.Text, 1, new string[] { "some_text" }, 1 })] public void OpenOnNodeType() { XmlNodeType nodeType = (XmlNodeType)Variation.Params[0]; int position = (int)Variation.Params[1]; string[] verif = (string[])Variation.Params[2]; int HowManyReads = (int)Variation.Params[3]; XDocument doc = XDocument.Load(new StringReader(_xml), LoadOptions.PreserveWhitespace); // Navigate to the required node int count = 0; XNode node = null; foreach (XNode n in doc.DescendantNodes().Where(x => x.NodeType == nodeType)) { if (position == count) { node = n; break; } count++; } using (XmlReader r = node.CreateReader()) { TestLog.Compare(r.ReadState, ReadState.Initial, "r.ReadState before Read()"); r.Read(); TestLog.Compare(r.ReadState, ReadState.Interactive, "r.ReadState after Read()"); TestLog.Compare(r.NodeType, (nodeType == XmlNodeType.Text && count == 0) ? XmlNodeType.Whitespace : nodeType, "r.NodeType"); // switch (nodeType) { case XmlNodeType.Element: TestLog.Compare(r.LocalName, verif[0], "r.LocalName"); TestLog.Compare(r.Prefix, verif[1], "r.Prefix"); TestLog.Compare(r.NamespaceURI, verif[2], "r.NamespaceURI"); break; case XmlNodeType.ProcessingInstruction: TestLog.Compare(r.LocalName, verif[0], "r.LocalName"); TestLog.Compare(r.Value, verif[1], "r.Value"); break; case XmlNodeType.Comment: case XmlNodeType.Text: TestLog.Compare(r.Value, verif[0], "r.Value"); break; } int nodeWalkCount = 0; do { nodeWalkCount++; while (r.MoveToNextAttribute()) { nodeWalkCount++; } } while (r.Read()); TestLog.Compare(r.ReadState, ReadState.EndOfFile, "r.ReadState after reading all"); } }
public static void UpdateXMLGingerVersion(XDocument xmlDoc, string gingerVersionToSet) { var comments = xmlDoc.DescendantNodes().OfType <XComment>(); string UpdatedComment = String.Format("Ginger Repository Item created with version: " + gingerVersionToSet); comments.ElementAt(0).ReplaceWith(new XComment(UpdatedComment)); }
public static XDocument AddProjectGuidToWebConfig(XDocument document, string projectGuid, bool ignoreProjectGuid) { try { if (document != null && !string.IsNullOrEmpty(projectGuid)) { IEnumerable <XComment> comments = document.DescendantNodes().OfType <XComment>(); projectGuid = projectGuid.Trim('{', '}', '(', ')').Trim(); string projectGuidValue = string.Format("ProjectGuid: {0}", projectGuid); XComment projectGuidComment = comments.FirstOrDefault(comment => string.Equals(comment.Value, projectGuidValue, StringComparison.OrdinalIgnoreCase)); if (projectGuidComment != null) { if (ignoreProjectGuid) { projectGuidComment.Remove(); } return(document); } if (!ignoreProjectGuid) { document.LastNode.AddAfterSelf(new XComment(projectGuidValue)); return(document); } } } catch { // This code path is only used for telemetry. } return(document); }
private void DecryptTriTechConfig() { string configFile = System.IO.Path.Combine(Environment.CurrentDirectory, "TriTech.config"); XDocument xmlDoc = XDocument.Load(configFile); var nodes = from item in xmlDoc.DescendantNodes() select item; foreach (XNode node in nodes) { if (node is XElement) { //listBox1.Items.Add((node as XElement).Name); if ((node as XElement).Name == "add") { string value = (node as XElement).Attribute("value").Value; (node as XElement).SetAttributeValue("value", Cryptography.Decrypt(value, "Europa")); } } //else // listBox1.Items.Add(node); } xmlDoc.Save("Clear_TriTech.config"); }
//加载动态脚本 static ScriptState LoadScript(XDocument xdoc) { if (xdoc.DescendantNodes() .Any(el => el.NodeType == XmlNodeType.CDATA)) { var scriptcode = ((XCData)xdoc.DescendantNodes() .Single(el => el.NodeType == XmlNodeType.CDATA) .Parent.FirstNode).Value; var script = CSharpScript.RunAsync(scriptcode).Result; return(script); } else { return(null); } }
public string GetExe(string path) { string newPath = System.IO.Path.GetDirectoryName(path) + "\\"; XDocument doc = XDocument.Parse(File.ReadAllText(path, Encoding.UTF8)); foreach (XNode node in doc.DescendantNodes()) { if (node is XElement) { XElement element = (XElement)node; if (element.Name.LocalName.Equals("AssemblyName")) { name = element; } if (element.Name.LocalName.Equals("OutputPath")) { output = element; newPath += output.Value + name.Value + ".exe"; return(newPath); } } } return(""); //Xelement output obsahuje bin/debug, xelement name obsahuje jméno "AppLauncher" }
private static void getXMLNode() { XDocument xml = XDocument.Load("C:/ConsioleProject/YieldProg/YieldProg/dataItem.xml"); XElement el1 = xml.Root; XElement el2 = xml.Element("documentIdentification"); //foreach (var node in xml.DescendantNodes().OfType<XText>()) //{ // var value = node.Value.Trim(); // if (!string.IsNullOrEmpty(value)) // { // Console.WriteLine(value); // //some code... // } //} var redactedElements = new HashSet <XName> { "number", "givenName" }; // List<XElement> elements = new List<XElement>(); //IEnumerable<XElement> childList = from el in xml.Descendants().Where(a=> a.Element("number")) // select el; foreach (XNode node in xml.DescendantNodes()) { if (node is XElement) { XElement element = (XElement)node; //XElement hash = element.Element("documentIdentification").Element("number"); var elements = element.Descendants() .Where(a => redactedElements.Contains(a.Name.LocalName)) .ToList(); foreach (var el in elements) { //var num = el.Descendants("number").Where(a => a.Parent.Name == "documentIdentification"); el.Value = new string('*', el.Value.Length); } //if (element.Name.LocalName.Equals("documentIdentification")) //{ // //string c1 = (string)element.Name.LocalName("number"); // var eg = element.Descendants("number"); // var elements = element.Descendants() // .Where(a => redactedElements.Contains(a.Name.LocalName)) // .ToList(); // foreach (var el in elements) // { // el.Value = new string('*', el.Value.Length); // } //} } } }
private static XElement ParseLog4NetDocument(XDocument configuration) { var element = configuration .DescendantNodes() .FirstOrDefault(e => e.NodeType == XmlNodeType.Element && ((XElement)e).Name == "log4net"); return((XElement)element); }
/// <summary> /// Returns a <see cref="ItemGroupContent"/> instance with an Include matching the given string, or null otherwise /// </summary> /// <typeparam name="T"></typeparam> /// <param name="include"></param> /// <returns></returns> public T FindItemGroupContent <T>(string include) where T : ItemGroupContent, new() { var node = _source.DescendantNodes() .Where(x => x is XElement) .FirstOrDefault( x => ((XElement)x).Name.LocalName == typeof(T).Name && ((XElement)x).Attributes().First(y => y.Name.LocalName == "Include").Value == include); if (node == null) { return(default(T)); } return((T)Activator.CreateInstance(typeof(T), new object[] { node })); }
public static IEnumerable <XNode> GetXNodes(string cspXml) { TextReader tr = new StringReader(cspXml); XDocument doc = XDocument.Load(tr); var xnodes = from node in doc.DescendantNodes() select node; return(xnodes); }
private void RemoveEmptyTextNodes(XDocument document) { var emptyTexts = document.DescendantNodes().OfType <XText>().Where(text => string.IsNullOrEmpty(text.Value?.Trim())).ToArray(); foreach (var emptyText in emptyTexts) { emptyText.Remove(); } }
private void RemoveComments(XDocument document) { var comments = document.DescendantNodes().OfType <XComment>().ToArray(); foreach (var comment in comments) { comment.Remove(); } }
private void ForceTags(XDocument document) { foreach (XElement childElement in from x in document.DescendantNodes().OfType <XElement>() where x.IsEmpty select x) { childElement.Value = string.Empty; } }
public void XLinq27() { XDocument doc = XDocument.Load("nw_customers.xml"); var query = doc.DescendantNodes().OfType <XText>().Select(t => t.Value); foreach (string result in query) { Console.WriteLine(result); } }
//[Variation(Priority = 0, Desc = "XDocument.Load(), Load options, LineInfo, Uri", Param = "Uri")] //[Variation(Priority = 0, Desc = "XDocument.Load(), Load options, LineInfo, Stream", Param = "Stream")] public void LoadOptionsLI() { string fileName = @"NoExternals.xml"; var how = CurrentChild.Param as string; XDocument doc = GetXDocument(fileName, LoadOptions.SetLineInfo, how); foreach (object node in doc.DescendantNodes().OfType <object>().Concat2(doc.Descendants().Attributes().OfType <object>())) { TestLog.Compare((node as IXmlLineInfo).LineNumber != 0, "LineNumber failed"); TestLog.Compare((node as IXmlLineInfo).LinePosition != 0, "LinePosition failed"); } doc = GetXDocument(fileName, LoadOptions.None, how); foreach (object node in doc.DescendantNodes().OfType <object>().Concat2(doc.Descendants().Attributes().OfType <object>())) { TestLog.Compare((node as IXmlLineInfo).LineNumber == 0, "LineNumber failed"); TestLog.Compare((node as IXmlLineInfo).LinePosition == 0, "LinePosition failed"); } }
private void saveXMLToSession(XDocument document) { foreach (XElement childElement in from x in document.DescendantNodes().OfType <XElement>() where x.IsEmpty select x) { childElement.Value = ""; } SessionHelper.current.saveForm = document; }
/// <summary> /// Returns a collection of descendant nodes for this document, including the document itself. /// </summary> /// <param name="document"></param> /// <returns></returns> public static IEnumerable <XNode> DescendantsAndSelf(this XDocument document) { Contract.Requires <ArgumentNullException>(document != null); yield return(document); foreach (var node in document.DescendantNodes()) { yield return(node); } }
private static XDocument ValidatesFieldsXDoc(XDocument xdoc) { DateTime t; bool b; xdoc .DescendantNodes() .Where(d => d.NodeType == XmlNodeType.Text && DateTime.TryParse(d.ToString(), out t)) .ToList() .ForEach(n => n.Parent.SetValue(DateTime.Parse(n.ToString()))); xdoc .DescendantNodes() .Where(d => d.NodeType == XmlNodeType.Text && Boolean.TryParse(d.ToString(), out b)) .ToList() .ForEach(n => n.Parent.SetValue(Boolean.Parse(n.ToString()))); return(xdoc); }
void DropNSFromDocument(XDocument doc) { if (!shouldDropNamespace) { return; } var attributes = doc.Descendants().SelectMany(n => n.Attributes()); var textNodes = doc.DescendantNodes().OfType <XText> ().ToArray(); DropNS(attributes, textNodes); }
static void ForceEmptyTagsWithNewlines(XDocument document) { // this is to force compatibility with previous implementation, // in particular, to support nested objects with null properties in them. foreach (var childElement in from x in document.DescendantNodes().OfType <XElement>() where x.IsEmpty && !x.HasAttributes select x) { childElement.Value = "\n"; } }
private static void SetDescriptionInXDoc(XDocument xDoc, string description) { var oldParent = xDoc.DescendantNodes().OfType <XElement>().Where(x => x.Name == "member").FirstOrDefault(); if (!string.IsNullOrWhiteSpace(description)) { var oldSummaryElement = xDoc .DescendantNodes().OfType <XElement>() .Where(x => x.Name == "summary") .FirstOrDefault(); if (oldSummaryElement != null) { oldSummaryElement.Value = description; } else { var newSummary = new XElement("summary", description); oldParent.AddFirst(newSummary); } } }
public static void DescendantNodesOnXDocBeforeAndAfter() { XElement a = new XElement("A", "a"), b = new XElement("B", "b"); a.Add(b); XDocument xDoc = new XDocument(a); IEnumerable <XNode> nodes = xDoc.DescendantNodes(); Assert.Equal(4, nodes.Count()); a.Remove(); Assert.Equal(0, nodes.Count()); }
static void Main(string[] args) { XDocument myxml = XDocument.Load(@"OGU20.kml"); IEnumerable <XNode> de = from el in myxml.DescendantNodes() select el; Console.WriteLine(de.Count <XNode>().ToString()); var z = myxml.Descendants("coordinates"); foreach (XElement x in z) { x.Value = x.Value + 100; } foreach (XElement xe in z) { string cordinateItem = ""; string item = xe.Value; string[] i = item.Split(',', ' '); foreach (string s in i) { double tempValue = Convert.ToDouble(s); if (tempValue == 0) { cordinateItem += "" + Convert.ToDouble(s).ToString() + ""; } if (tempValue > 0 && tempValue < 5) { cordinateItem += " " + (Convert.ToDouble(s) + 45).ToString() + ","; } if (tempValue < -150 && tempValue > -190) { cordinateItem += " " + (Convert.ToDouble(s) + 191).ToString() + ","; } } xe.SetValue(cordinateItem); } myxml.Save(@"OGU20.kml"); foreach (XElement xe in z) { Console.WriteLine(xe.ToString()); } Console.ReadLine(); }
//[Variation(Priority = 0, Desc = "Connected nodes")] public void ConnectedNodes() { XDocument doc = XDocument.Parse("\n<?PI?><!--comm1--><A>t1\t<B xmlns='nsb'><C/><!--cpmm--><![CDATA[hey]]></B>t2<D>string\tonly</D></A>", LoadOptions.PreserveWhitespace); IEnumerable <XNode> nodes = GetDescendantNodes(doc, true); TestLog.Compare(doc.DescendantNodes().Count() + 1, nodes.Count(), "TEST_FAILED: Selection method failed"); foreach (XNode n1 in nodes) { foreach (XNode n2 in nodes) { VerifyOrder(nodes, n1, n2); } } }
private void CommentFirstXElement(out XDocument xdoc, out int origTransCount, out int origCommentCount) { TransactionAdapterTests.FillTransactionAdapter(); xdoc = TransactionAdapterTests.TestXDoc; origTransCount = xdoc.Root.Elements(GranitXml.Constants.Transaction).Count(); origCommentCount = xdoc.DescendantNodes().Where(x => x.NodeType == XmlNodeType.Comment).Count(); XElement xe = xdoc.Root.Elements(GranitXml.Constants.Transaction) .Where(x => TransactionAdapterTests.TestAdapter.IsBindedWith(x)).ToList() .FirstOrDefault(); xdoc.CommentXElmenet(xe); }
private static bool EmbeddedResourceExists(string relativePath, XDocument doc) { var existingRef = doc.DescendantNodes().OfType <XElement>() .FirstOrDefault(n => n.Name.LocalName == "EmbeddedResource" && Path.GetFileName(n.Attribute("Include").Value) == Path.GetFileName(relativePath)); if (existingRef != null && !File.Exists(existingRef.Attribute("Include").Value)) { existingRef.Remove(); return(false); } return(existingRef != null); }
public static WorkerSettings GetSettings(XDocument xDocument) { var setting = new WorkerSettings(); if (xDocument.Root == null) { return(setting); } var appId = xDocument.DescendantNodes().OfType <XElement>().First(x => x.Name == "AppId"); setting.AppId = Convert.ToInt32(appId.Value); var email = xDocument.DescendantNodes().OfType <XElement>().First(x => x.Name == "email"); if (!String.IsNullOrEmpty(email.Value)) { setting.Email = email.Value; } var pass = xDocument.DescendantNodes().OfType <XElement>().First(x => x.Name == "pass"); if (!String.IsNullOrEmpty(pass.Value)) { setting.Pass = pass.Value; } var token = xDocument.DescendantNodes().OfType <XElement>().First(x => x.Name == "token"); if (!String.IsNullOrEmpty(token.Value)) { setting.Token = token.Value; } var userId = xDocument.DescendantNodes().OfType <XElement>().First(x => x.Name == "userId"); if (!String.IsNullOrEmpty(userId.Value)) { setting.UserId = Convert.ToInt32(userId.Value); } return(setting); }
private XElement GetElement(XDocument doc, string elementName) { foreach (XNode node in doc.DescendantNodes()) { if (node is XElement) { XElement element = (XElement)node; if (element.Name.LocalName.Equals(elementName)) { return(element); } } } return(null); }
public void LoadOptionsBU() { string fileName = @"NoExternals.xml"; var how = CurrentChild.Param as string; XDocument doc = GetXDocument(fileName, LoadOptions.SetBaseUri, how); foreach (XObject node in doc.DescendantNodes().OfType <object>().Concat2(doc.Descendants().Attributes().OfType <object>())) { string baseUri = node.BaseUri; // fail when use stream replace file if (!string.IsNullOrWhiteSpace(baseUri)) { TestLog.Compare(new Uri(baseUri), new Uri(GetFullTestPath(fileName)), "base uri failed"); } } doc = GetXDocument(fileName, LoadOptions.None, how); foreach (XObject node in doc.DescendantNodes().OfType <object>().Concat2(doc.Descendants().Attributes().OfType <object>())) { string baseUri = node.BaseUri; TestLog.Compare(baseUri, "", "base uri failed"); } }
/// <summary> /// Force tags to be non-selfclosing /// </summary> /// <param name="document"></param> public static void ForceTags(this XDocument document) { var allowedSelfClosingTags = new HashSet <string> { "br", "img", "qti-stylesheet", "qti-text-entry-interaction" }; foreach (var childElement in from x in document.DescendantNodes().OfType <XElement>() where x.IsEmpty && !allowedSelfClosingTags.Contains(x.Name.LocalName.ToLower()) select x) { childElement.Value = string.Empty; } }
public static void DescendantNodesOnXDocBeforeAndAfter() { XElement a = new XElement("A", "a"), b = new XElement("B", "b"); a.Add(b); XDocument xDoc = new XDocument(a); IEnumerable<XNode> nodes = xDoc.DescendantNodes(); Assert.Equal(4, nodes.Count()); a.Remove(); Assert.Equal(0, nodes.Count()); }