public void ContainerAdd() { XElement element = new XElement("foo"); // Adding null does nothing. element.Add(null); Assert.Empty(element.Nodes()); // Add node, attrbute, string, some other value, and an IEnumerable. XComment comment = new XComment("this is a comment"); XComment comment2 = new XComment("this is a comment 2"); XComment comment3 = new XComment("this is a comment 3"); XAttribute attribute = new XAttribute("att", "att-value"); string str = "this is a string"; int other = 7; element.Add(comment); element.Add(attribute); element.Add(str); element.Add(other); element.Add(new XComment[] { comment2, comment3 }); Assert.Equal( new XNode[] { comment, new XText(str + other), comment2, comment3 }, element.Nodes(), XNode.EqualityComparer); Assert.Equal(new[] { attribute.Name }, element.Attributes().Select(x => x.Name)); Assert.Equal(new[] { attribute.Value }, element.Attributes().Select(x => x.Value)); element.RemoveAll(); Assert.Empty(element.Nodes()); // Now test params overload. element.Add(comment, attribute, str, other); Assert.Equal(new XNode[] { comment, new XText(str + other) }, element.Nodes(), XNode.EqualityComparer); Assert.Equal(new[] { attribute.Name }, element.Attributes().Select(x => x.Name)); Assert.Equal(new[] { attribute.Value }, element.Attributes().Select(x => x.Value)); // Not allowed to add a document as a child. XDocument document = new XDocument(); Assert.Throws<ArgumentException>(() => element.Add(document)); }
internal DestinationProjXml(string destProj) { DestProjAbsolutePath = PathMaker.MakeAbsolutePathFromPossibleRelativePathOrDieTrying(null, destProj); DestProjDirectory = Path.GetDirectoryName(DestProjAbsolutePath) ?? ""; try { DestProjXdoc = XDocument.Load(DestProjAbsolutePath); RootXelement = DestProjXdoc.Element(Settings.MSBuild + "Project"); ItemGroups = RootXelement?.Elements(Settings.MSBuild + "ItemGroup").ToList(); } catch (Exception e) { App.Crash(e, "Crash: DestProjXml CTOR loading destination XML from " + DestProjAbsolutePath); } if (RootXelement == null) App.Crash("Crash: No MSBuild Namespace in " + DestProjAbsolutePath); StartPlaceHolder = FindCommentOrCrashIfDuplicatesFound(Settings.StartPlaceholderComment); EndPlaceHolder = FindCommentOrCrashIfDuplicatesFound(Settings.EndPlaceholderComment); if (StartPlaceHolder == null && RootXelement != null) { XElement lastItemGroup = ItemGroups?.Last(); lastItemGroup?.AddAfterSelf(new XComment(Settings.EndPlaceholderComment)); lastItemGroup?.AddAfterSelf(new XComment(Settings.StartPlaceholderComment)); StartPlaceHolder = FindCommentOrCrashIfDuplicatesFound(Settings.StartPlaceholderComment); EndPlaceHolder = FindCommentOrCrashIfDuplicatesFound(Settings.EndPlaceholderComment); } OldLinkedXml = ReadLinkedXml(); Keepers = new List<XElement>(); }
/// <summary> /// Clones any XObject into another one. /// </summary> /// <param name="this">This XObject to clone.</param> /// <param name="setLineColumnInfo">False to not propagate any associated <see cref="IXmlLineInfo"/> to the cloned object.</param> /// <returns>A clone of this object.</returns> public static T Clone <T>(this T @this, bool setLineColumnInfo = true) where T : XObject { XObject o = null; switch (@this) { case null: return(null); case XAttribute a: o = new XAttribute(a); break; case XElement e: o = new XElement(e.Name, e.Attributes().Select(a => a.Clone()), e.Nodes().Select(n => n.Clone())); break; case XComment c: o = new XComment(c); break; case XCData d: o = new XCData(d); break; case XText t: o = new XText(t); break; case XProcessingInstruction p: o = new XProcessingInstruction(p); break; case XDocument d: o = new XDocument(new XDeclaration(d.Declaration), d.Nodes().Select(n => n.Clone())); break; case XDocumentType t: o = new XDocumentType(t); break; default: throw new NotSupportedException(@this.GetType().AssemblyQualifiedName); } return(setLineColumnInfo ? (T)o.SetLineColumnInfo(@this) : (T)o); }
static void Main(string[] args) { Console.Write("\n Create XML file using XDocument"); Console.Write("\n =================================\n"); XDocument xml = new XDocument(); xml.Declaration = new XDeclaration("1.0", "utf-8", "yes"); /* * It is a quirk of the XDocument class that the XML declaration, * a valid processing instruction element, cannot be added to the * XDocument's element collection. Instead, it must be assigned * to the document's Declaration property. */ XComment comment = new XComment("Demonstration XML"); xml.Add(comment); XElement root = new XElement("root"); xml.Add(root); XElement child1 = new XElement("child1", "child1 content"); XElement child2 = new XElement("child2"); XElement grandchild21 = new XElement("grandchild21", "content of grandchild21"); child2.Add(grandchild21); root.Add(child1); root.Add(child2); Console.Write("\n{0}\n", xml.Declaration); Console.Write(xml.ToString()); Console.Write("\n\n"); }
public XComment(XComment other) { if (other == null) { throw new ArgumentNullException("other"); } this.value = other.value; }
XCommentSection(string name, string startMarker, string endMarker, XComment start, XComment end) { Name = name; _startMarker = startMarker; _endMarker = endMarker; _start = start; _end = end; }
public void CreateCommentSimple() { Assert.Throws<ArgumentNullException>(() => new XComment((string)null)); XComment c = new XComment("foo"); Assert.Equal("foo", c.Value); Assert.Null(c.Parent); }
/// <summary> /// Copy ctor /// </summary> public XComment(XComment source) { if (source == null) { throw new ArgumentNullException("source"); } value = source.value; }
/// <summary> /// Compares two comments using the indicated comparison options. /// </summary> /// <param name="c1">The first comment to compare.</param> /// <param name="c2">The second comment to compare.</param> /// <param name="options">The options to use in the comparison.</param> /// <returns>true if the comments are equal, false otherwise.</returns> public static bool DeepEquals(this XComment c1, XComment c2, ComparisonOptions options) { if ((c1 ?? c2) == null) return true; if ((c1 == null) || (c2 == null)) return false; // They are not both null, so if either is, then the other isn't return c1.Value == c2.Value; }
public void CreateDocumentWithContent() { XDeclaration declaration = new XDeclaration("1.0", "utf-8", "yes"); XComment comment = new XComment("This is a document"); XProcessingInstruction instruction = new XProcessingInstruction("doc-target", "doc-data"); XElement element = new XElement("RootElement"); XDocument doc = new XDocument(declaration, comment, instruction, element); Assert.Equal(new XNode[] { comment, instruction, element }, doc.Nodes()); }
//[Variation(Priority = 0, Desc = "XComment - not equals, hashconflict", Params = new object[] { "AAAAP", "AAAAQ", false })] //[Variation(Priority = 0, Desc = "XComment - equals", Params = new object[] { "AAAAP", "AAAAP", true })] //[Variation(Priority = 3, Desc = "XComment - Whitespaces (negative)", Params = new object[] { " ", " ", false })] //[Variation(Priority = 3, Desc = "XComment - Whitespaces", Params = new object[] { " ", " ", true })] //[Variation(Priority = 1, Desc = "XComment - Empty", Params = new object[] { "", "", true })] public void Comment() { bool expected = (bool)Variation.Params[2]; XComment c1 = new XComment(Variation.Params[0] as string); XComment c2 = new XComment(Variation.Params[1] as string); VerifyComparison(expected, c1, c2); XDocument doc = new XDocument(c1); XElement e2 = new XElement("p2p", c2); VerifyComparison(expected, c1, c2); }
public void CommentEquals() { XComment c1 = new XComment("xxx"); XComment c2 = new XComment("xxx"); XComment c3 = new XComment("yyy"); Assert.False(c1.Equals(null)); Assert.False(c1.Equals("foo")); Assert.True(c1.Equals(c1)); Assert.False(c1.Equals(c2)); Assert.False(c1.Equals(c3)); }
private static async Task <XNode> ReadFromAsyncInternal(XmlReader reader, CancellationToken cancellationToken) { if (reader.ReadState != ReadState.Interactive) { throw new InvalidOperationException(SR.InvalidOperation_ExpectedInteractive); } XNode ret; switch (reader.NodeType) { case XmlNodeType.Text: case XmlNodeType.SignificantWhitespace: case XmlNodeType.Whitespace: ret = new XText(reader.Value); break; case XmlNodeType.CDATA: ret = new XCData(reader.Value); break; case XmlNodeType.Comment: ret = new XComment(reader.Value); break; case XmlNodeType.DocumentType: var name = reader.Name; var publicId = reader.GetAttribute("PUBLIC"); var systemId = reader.GetAttribute("SYSTEM"); var internalSubset = reader.Value; ret = new XDocumentType(name, publicId, systemId, internalSubset); break; case XmlNodeType.Element: return(await XElement.CreateAsync(reader, cancellationToken).ConfigureAwait(false)); case XmlNodeType.ProcessingInstruction: var target = reader.Name; var data = reader.Value; ret = new XProcessingInstruction(target, data); break; default: throw new InvalidOperationException(SR.Format(SR.InvalidOperation_UnexpectedNodeType, reader.NodeType)); } cancellationToken.ThrowIfCancellationRequested(); await reader.ReadAsync().ConfigureAwait(false); return(ret); }
public void CommentValue() { XComment c = new XComment("xxx"); Assert.Equal("xxx", c.Value); // Null value not allowed. Assert.Throws<ArgumentNullException>(() => c.Value = null); // Try setting a value. c.Value = "abcd"; Assert.Equal("abcd", c.Value); }
/// <summary> /// Validate behavior of the XDocument copy/clone constructor. /// </summary> /// <returns>true if pass, false if fail</returns> //[Variation(Desc = "CreateDocumentCopy")] public void CreateDocumentCopy() { try { new XDocument((XDocument)null); Validate.ExpectedThrow(typeof(ArgumentNullException)); } catch (Exception ex) { Validate.Catch(ex, typeof(ArgumentNullException)); } XDeclaration declaration = new XDeclaration("1.0", "utf-8", "yes"); XComment comment = new XComment("This is a document"); XProcessingInstruction instruction = new XProcessingInstruction("doc-target", "doc-data"); XElement element = new XElement("RootElement"); XDocument doc = new XDocument(declaration, comment, instruction, element); XDocument doc2 = new XDocument(doc); IEnumerator e = doc2.Nodes().GetEnumerator(); // First node: declaration Validate.IsEqual(doc.Declaration.ToString(), doc2.Declaration.ToString()); // Next node: comment Validate.IsEqual(e.MoveNext(), true); Validate.Type(e.Current, typeof(XComment)); Validate.IsNotReferenceEqual(e.Current, comment); XComment comment2 = (XComment)e.Current; Validate.IsEqual(comment2.Value, comment.Value); // Next node: processing instruction Validate.IsEqual(e.MoveNext(), true); Validate.Type(e.Current, typeof(XProcessingInstruction)); Validate.IsNotReferenceEqual(e.Current, instruction); XProcessingInstruction instruction2 = (XProcessingInstruction)e.Current; Validate.String(instruction2.Target, instruction.Target); Validate.String(instruction2.Data, instruction.Data); // Next node: element. Validate.IsEqual(e.MoveNext(), true); Validate.Type(e.Current, typeof(XElement)); Validate.IsNotReferenceEqual(e.Current, element); XElement element2 = (XElement)e.Current; Validate.ElementName(element2, element.Name.ToString()); Validate.Count(element2.Nodes(), 0); // Should be end. Validate.IsEqual(e.MoveNext(), false); }
/// <summary> /// Tests the Add methods on Container. /// </summary> /// <param name="context"></param> /// <returns></returns> //[Variation(Desc = "ContainerAdd")] public void ContainerAdd() { XElement element = new XElement("foo"); // Adding null does nothing. element.Add(null); Validate.Count(element.Nodes(), 0); // Add node, attrbute, string, some other value, and an IEnumerable. XComment comment = new XComment("this is a comment"); XComment comment2 = new XComment("this is a comment 2"); XComment comment3 = new XComment("this is a comment 3"); XAttribute attribute = new XAttribute("att", "att-value"); string str = "this is a string"; int other = 7; element.Add(comment); element.Add(attribute); element.Add(str); element.Add(other); element.Add(new XComment[] { comment2, comment3 }); Validate.EnumeratorDeepEquals( element.Nodes(), new XNode[] { comment, new XText(str + other), comment2, comment3 }); Validate.EnumeratorAttributes(element.Attributes(), new XAttribute[] { attribute }); element.RemoveAll(); Validate.Count(element.Nodes(), 0); // Now test params overload. element.Add(comment, attribute, str, other); Validate.EnumeratorDeepEquals( element.Nodes(), new XNode[] { comment, new XText(str + other) }); Validate.EnumeratorAttributes(element.Attributes(), new XAttribute[] { attribute }); // Not allowed to add a document as a child. XDocument document = new XDocument(); try { element.Add(document); Validate.ExpectedThrow(typeof(ArgumentException)); } catch (Exception ex) { Validate.Catch(ex, typeof(ArgumentException)); } }
public void CommentDeepEquals() { XComment c1 = new XComment("xxx"); XComment c2 = new XComment("xxx"); XComment c3 = new XComment("yyy"); Assert.False(XNode.DeepEquals(c1, (XComment)null)); Assert.True(XNode.DeepEquals(c1, c1)); Assert.True(XNode.DeepEquals(c1, c2)); Assert.False(XNode.DeepEquals(c1, c3)); Assert.Equal(XNode.EqualityComparer.GetHashCode(c1), XNode.EqualityComparer.GetHashCode(c2)); }
//constructor in which all the member variables are initialised public XmlGenerator() { try { xmlDocument = new XDocument(); xmlDocument.Declaration = new XDeclaration("1.0", "utf-8", "yes"); xmlDocumentComment = new XComment("Generates XML Output for the Analyzed data"); xmRootElement = new XElement("AnalysisResult"); } catch { Console.WriteLine("Error occurred while generating the XML file"); } }
public void NodeTypes() { XDocument document = new XDocument(); XElement element = new XElement("x"); XText text = new XText("text-value"); XComment comment = new XComment("comment"); XProcessingInstruction processingInstruction = new XProcessingInstruction("target", "data"); Assert.Equal(XmlNodeType.Document, document.NodeType); Assert.Equal(XmlNodeType.Element, element.NodeType); Assert.Equal(XmlNodeType.Text, text.NodeType); Assert.Equal(XmlNodeType.Comment, comment.NodeType); Assert.Equal(XmlNodeType.ProcessingInstruction, processingInstruction.NodeType); }
public static void InitDebils() { XDocument Debili = new XDocument(); XDeclaration Xdec = new XDeclaration("1.0", "utf-8", "yes"); XComment Com = new XComment("Не изменяйте нижнюю строчку"); XElement Stud = new XElement("StudList", new XElement("Class", new XAttribute("ID", 1), new XElement("Name", "Витек Мартынов"), new XElement("Name", "Батруха Иисусов"), new XElement("Name", "Шланг Волосатый"))); //Debili.Add(Xdec); Debili.Add(Stud); Debili.Save("Test.xml"); }
//[Variation(Desc = "NodeTypes")] public void NodeTypes() { XDocument document = new XDocument(); XElement element = new XElement("x"); XText text = new XText("text-value"); XComment comment = new XComment("comment"); XProcessingInstruction processingInstruction = new XProcessingInstruction("target", "data"); Validate.IsEqual(document.NodeType, XmlNodeType.Document); Validate.IsEqual(element.NodeType, XmlNodeType.Element); Validate.IsEqual(text.NodeType, XmlNodeType.Text); Validate.IsEqual(comment.NodeType, XmlNodeType.Comment); Validate.IsEqual(processingInstruction.NodeType, XmlNodeType.ProcessingInstruction); }
public void SaveToXmlFile(string fileName) { XDocument xDoc = new XDocument {Declaration = new XDeclaration("1.0", "utf-8", "yes")}; XComment xComment = new XComment("Manga Reading Assistant Database Exporter"); xDoc.Add(xComment, new XElement("MangaDatabase")); if (xDoc.Root != null) { xDoc.Root.Add(PublisherXElement(DatabaseWrapper.Instance.GetAllPublisherInfoElements())); xDoc.Root.Add(GenresXElement(DatabaseWrapper.Instance.GetAllGenreInfoElements())); xDoc.Root.Add(AuthorXElement(DatabaseWrapper.Instance.GetAllAuthorInfoElements())); xDoc.Root.Add(MangaXElement(DatabaseWrapper.Instance.GetAllMangaInfoElements())); xDoc.Root.Add(MangaGenreXElement(DatabaseWrapper.Instance.GetAllMangaGenreElements())); xDoc.Root.Add(MangaAuthorsXElement(DatabaseWrapper.Instance.GetAllMangaAuthorElements())); } xDoc.Save(fileName); }
public void CreateDocumentCopy() { Assert.Throws<ArgumentNullException>(() => new XDocument((XDocument)null)); XDeclaration declaration = new XDeclaration("1.0", "utf-8", "yes"); XComment comment = new XComment("This is a document"); XProcessingInstruction instruction = new XProcessingInstruction("doc-target", "doc-data"); XElement element = new XElement("RootElement"); XDocument doc = new XDocument(declaration, comment, instruction, element); XDocument doc2 = new XDocument(doc); IEnumerator e = doc2.Nodes().GetEnumerator(); // First node: declaration Assert.Equal(doc.Declaration.ToString(), doc2.Declaration.ToString()); // Next node: comment Assert.True(e.MoveNext()); Assert.IsType<XComment>(e.Current); Assert.NotSame(comment, e.Current); XComment comment2 = (XComment)e.Current; Assert.Equal(comment.Value, comment2.Value); // Next node: processing instruction Assert.True(e.MoveNext()); Assert.IsType<XProcessingInstruction>(e.Current); Assert.NotSame(instruction, e.Current); XProcessingInstruction instruction2 = (XProcessingInstruction)e.Current; Assert.Equal(instruction.Target, instruction2.Target); Assert.Equal(instruction.Data, instruction2.Data); // Next node: element. Assert.True(e.MoveNext()); Assert.IsType<XElement>(e.Current); Assert.NotSame(element, e.Current); XElement element2 = (XElement)e.Current; Assert.Equal(element.Name.ToString(), element2.Name.ToString()); Assert.Empty(element2.Nodes()); // Should be end. Assert.False(e.MoveNext()); }
//--------------------<displays the Function Analysis in XML format>----------------------------- public void displayFunctionAnalysis() { List<Elem> outputList = OutputRepository.output_; if (outputList.Count == 0) { Console.Write("No Data in FunctionAnalysis"); return; } Console.Write("\n Created XML for Function size and Complexity"); Console.Write("\n =====================================\n"); XDocument xml = new XDocument(); xml.Declaration = new XDeclaration("1.0", "utf-8", "yes"); XComment comment = new XComment("Demonstration XML"); xml.Add(comment); XElement root = new XElement("CODEANALYSIS"); xml.Add(root); foreach (Elem e in outputList) { //Addition of Child int size = e.end - e.begin; XElement childType = new XElement("Type"); root.Add(childType); XElement type = new XElement("Type", e.type); childType.Add(type); XElement childName = new XElement("NAME"); root.Add(childName); XElement name = new XElement("Name", e.name); childName.Add(name); XElement childComplexity = new XElement("COMPLEXITY"); root.Add(childComplexity); XElement functionComplexity = new XElement("Complexity", Convert.ToString(e.functionComplexity)); childComplexity.Add(functionComplexity); XElement childSize = new XElement("SIZE"); root.Add(childSize); XElement sizeNew = new XElement("Size", Convert.ToString(size)); childSize.Add(sizeNew); xml.Save(Directory.GetCurrentDirectory() + "\\FunctionAnalysis.xml"); } Console.Write(" The Size and Complexity XML file is displayed at:\n"); Console.Write(" "); Console.Write(Directory.GetCurrentDirectory()); Console.Write("\\FunctionAnalysis.xml"); Console.Write("\n\n"); }
internal static XNode ReadFrom(XmlReader r, LoadOptions options) { switch (r.NodeType) { case XmlNodeType.Element: return(XElement.LoadCore(r, options)); case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: case XmlNodeType.Text: XText t = new XText(r.Value); t.FillLineInfoAndBaseUri(r, options); r.Read(); return(t); case XmlNodeType.CDATA: XCData c = new XCData(r.Value); c.FillLineInfoAndBaseUri(r, options); r.Read(); return(c); case XmlNodeType.ProcessingInstruction: XPI pi = new XPI(r.Name, r.Value); pi.FillLineInfoAndBaseUri(r, options); r.Read(); return(pi); case XmlNodeType.Comment: XComment cm = new XComment(r.Value); cm.FillLineInfoAndBaseUri(r, options); r.Read(); return(cm); case XmlNodeType.DocumentType: XDocumentType d = new XDocumentType(r.Name, r.GetAttribute("PUBLIC"), r.GetAttribute("SYSTEM"), r.Value); d.FillLineInfoAndBaseUri(r, options); r.Read(); return(d); default: throw new InvalidOperationException(String.Format("Node type {0} is not supported", r.NodeType)); } }
/* * It is a quirk of the XDocument class that the XML declaration, * a valid element, cannot be added to the XDocument's element * collection. Instead, it must be assigned to the document's * Declaration property. */ /* * we are creating XElements for each DBElement<int, string> in * DBEngine<int, DBElement<int, string>> using XElement object * We are saving XMl file to ~/TestExec/bin/debug/Test_DB.xml */ public static void create_xml_from_db(this DBEngine<int, DBElement<int, string>> db, Boolean persist) { XDocument xml = new XDocument(); xml.Declaration = new XDeclaration("1.0", "utf-8", "yes"); XComment comment = new XComment("Test DB data to XML"); xml.Add(comment); XElement root = new XElement("noSQL"); xml.Add(root); XElement keytype = new XElement("keytype", "integer"); root.Add(keytype); XElement payloadtype = new XElement("payloadtype", "string"); root.Add(payloadtype); foreach (var db_key in db.Keys()) { DBElement<int, string> ele = new DBElement<int, string>(); db.getValue(db_key, out ele); XElement key = new XElement("key", db_key); root.Add(key); XElement element = new XElement("element"); XElement name = new XElement("name", ele.name); XElement descr = new XElement("descr", ele.descr); XElement timestamp = new XElement("timestamp", ele.timeStamp); XElement children = new XElement("children"); XElement payload = new XElement("payload", ele.payload); foreach (int x in ele.children) { XElement children_key = new XElement("key", x); children.Add(children_key); } element.Add(name); element.Add(descr); element.Add(timestamp); element.Add(children); element.Add(payload); root.Add(element); } WriteLine(); //<--------Writing to XML---------> "Creating XML file using XDocument and writing into Test_DB.xml".title(); xml.Save("Test_DB.xml"); display_xml(xml, persist); WriteLine(); }
// ---------------< store output for option R >---------------- private void xmlForRelation() { List<ElemRelation> relation = RepositoryForRelation.storageForRelationship_; int relation_size = relation.Count; if (relation_size == 0) return; if (relation.Count == 0) { Console.Write("\n There is not Relationship Data for XML File. "); return; } Console.Write("\n Create XML file using XDocument for Relationship"); Console.Write("\n ================================================\n\n"); XDocument xml = new XDocument(); xml.Declaration = new XDeclaration("1.0", "utf-8", "yes"); XComment comment = new XComment("Demonstration XML"); xml.Add(comment); XElement root = new XElement("CODEANALYSIS"); xml.Add(root); foreach (ElemRelation e in relation) { XElement relationship = new XElement("RelationshipType"); root.Add(relationship); XElement relationshipType = new XElement("Relation", Convert.ToString(e.relationType)); relationship.Add(relationshipType); XElement from = new XElement("FROM"); root.Add(from); XElement fromF = new XElement("From", Convert.ToString(e.fromName)); from.Add(fromF); XElement to = new XElement("TO"); root.Add(to); XElement toF = new XElement("To", Convert.ToString(e.toName)); to.Add(toF); xml.Save("X_Relationship_Data.xml"); } Console.Write(" The Relationships is stored in:\n"); Console.Write(" " + Directory.GetCurrentDirectory() + "\\X_Relationship_Data.xml\n\n\n"); }
static void GenerateSnippets(string fileName) { Console.WriteLine(fileName); TextReader reader = File.OpenText(fileName); XElement root = new XElement("examples"); XDocument xd = new XDocument(root); XComment comment = new XComment("This file was generated by SnipGen.exe"); xd.Root.Add(comment); while (true) { string line = reader.ReadLine(); if (line == null) break; if (String.IsNullOrWhiteSpace(line)) continue; string[] tokens = line.Split(','); if (tokens.Length != 3) throw new Exception("Malformed line: + line"); string id = tokens[0].Trim(); Console.WriteLine("\t{0}", id); string source = Path.Combine(sourceRootDir,tokens[1].Trim()); string start = tokens[2].Trim(); XElement item = new XElement("item"); item.SetAttributeValue("id", id); root.Add(item); XElement sampleCode = new XElement("sampleCode"); sampleCode.SetAttributeValue("language", "CSharp"); sampleCode.Value = GetCode(source, start) + " "; item.Add(sampleCode); } xd.Save(Path.ChangeExtension(fileName,".snippets")); }
/// <summary> /// Method create xml document /// </summary> public void CreateDocument() { XElement drugsList = new XElement("DrugList"); DateTime thisDay = DateTime.Now; XComment koment = new XComment("DRUGS EXPORT, generated by NIS application. Date: " + thisDay); drugsList.Add(koment); foreach (var drug in _drugList) { XElement drugTag = new XElement("Drug"); XElement barCode = new XElement("BarCode", drug.BarCode); XElement drugName = new XElement("DrugName", drug.DrugName); XElement activeSubstance = new XElement("ActiveSubstance", drug.ActiveSubstance); XElement suklCode = new XElement("SuklCode", drug.SuklCode); XElement onPrescription = new XElement("OnPrescription", drug.OnPrescription); XElement price = new XElement("Price", drug.Price); XElement patientInfoLeaflet = new XElement("PatientInfoLeaflet", drug.PatientInfoLeaflet); XElement distributor = new XElement("Corporation", drug.Distributor); XAttribute regNumber = new XAttribute("registrationNumber", drug.DistributorRegNumber); XAttribute corporation = new XAttribute("corporation", drug.Corporation ?? ""); distributor.Add(regNumber); distributor.Add(corporation); drugTag.Add(barCode); drugTag.Add(drugName); drugTag.Add(activeSubstance); drugTag.Add(suklCode); drugTag.Add(onPrescription); drugTag.Add(price); drugTag.Add(patientInfoLeaflet); drugTag.Add(distributor); drugsList.Add(drugTag); } drugsList.Save("test.xml"); Process.Start("test.xml"); }
public void EscapeSequentialDashes () { XComment c; c = new XComment ("<--foo-->"); Assert.AreEqual ("<--foo-->", c.Value, "#1"); // bug #23318 // Unlike XmlWriter.WriteComment(), XComment.ToString() seems to accept "--" in the value. Assert.AreEqual ("<!--<- -foo- ->-->", c.ToString (), "#2"); // make sure if it can be read... XmlReader.Create (new StringReader (c.ToString ())).Read (); // The last '-' causes some glitch... c = new XComment ("--foo--"); Assert.AreEqual ("--foo--", c.Value, "#3"); Assert.AreEqual ("<!--- -foo- D;-->", c.ToString (), "#4"); XmlReader.Create (new StringReader (c.ToString ())).Read (); // What if <!-- appears in the value? c = new XComment ("<!--foo-->"); Assert.AreEqual ("<!--foo-->", c.Value, "#5"); Assert.AreEqual ("<!--<!- -foo- ->-->", c.ToString (), "#6"); XmlReader.Create (new StringReader (c.ToString ())).Read (); }
public void XCommentChangeValue() { XComment toChange = new XComment("Original Value"); String newValue = "New Value"; XElement xElem = new XElement("root", toChange); XElement xElemOriginal = new XElement(xElem); using (UndoManager undo = new UndoManager(xElem)) { undo.Group(); using (EventsHelper eHelper = new EventsHelper(xElem)) { using (EventsHelper comHelper = new EventsHelper(toChange)) { toChange.Value = newValue; Assert.True(toChange.Value.Equals(newValue), "Value did not change"); xElem.Verify(); comHelper.Verify(XObjectChange.Value, toChange); } eHelper.Verify(XObjectChange.Value, toChange); } undo.Undo(); Assert.True(XNode.DeepEquals(xElem, xElemOriginal), "Undo did not work!"); } }
public XComment(XComment other) { this.value = other.value; }
public void ElementDescendents() { 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[] { level1, level2, level3 }, level1.DescendantsAndSelf(), XNode.EqualityComparer); Assert.Equal( new XNode[] { level0, level1, level2, level3, comment }, level0.DescendantNodesAndSelf(), XNode.EqualityComparer); Assert.Empty(level0.DescendantsAndSelf(null)); Assert.Equal(new XElement[] { level0, level1 }, level0.DescendantsAndSelf("Level1"), XNode.EqualityComparer); }
internal void ReadContentFrom(XmlReader r, LoadOptions o) { if ((o & (LoadOptions.SetBaseUri | LoadOptions.SetLineInfo)) == 0) { ReadContentFrom(r); return; } if (r.ReadState != ReadState.Interactive) { throw new InvalidOperationException(SR.InvalidOperation_ExpectedInteractive); } XContainer c = this; XNode n = null; NamespaceCache eCache = new NamespaceCache(); NamespaceCache aCache = new NamespaceCache(); string baseUri = (o & LoadOptions.SetBaseUri) != 0 ? r.BaseURI : null; IXmlLineInfo li = (o & LoadOptions.SetLineInfo) != 0 ? r as IXmlLineInfo : null; do { string uri = r.BaseURI; switch (r.NodeType) { case XmlNodeType.Element: { XElement e = new XElement(eCache.Get(r.NamespaceURI).GetName(r.LocalName)); if (baseUri != null && baseUri != uri) { e.SetBaseUri(uri); } if (li != null && li.HasLineInfo()) { e.SetLineInfo(li.LineNumber, li.LinePosition); } if (r.MoveToFirstAttribute()) { do { XAttribute a = new XAttribute(aCache.Get(r.Prefix.Length == 0 ? string.Empty : r.NamespaceURI).GetName(r.LocalName), r.Value); if (li != null && li.HasLineInfo()) { a.SetLineInfo(li.LineNumber, li.LinePosition); } e.AppendAttributeSkipNotify(a); } while (r.MoveToNextAttribute()); r.MoveToElement(); } c.AddNodeSkipNotify(e); if (!r.IsEmptyElement) { c = e; if (baseUri != null) { baseUri = uri; } } break; } case XmlNodeType.EndElement: { if (c.content == null) { c.content = string.Empty; } // Store the line info of the end element tag. // Note that since we've got EndElement the current container must be an XElement XElement e = c as XElement; Debug.Assert(e != null, "EndElement received but the current container is not an element."); if (e != null && li != null && li.HasLineInfo()) { e.SetEndElementLineInfo(li.LineNumber, li.LinePosition); } if (c == this) { return; } if (baseUri != null && c.HasBaseUri) { baseUri = c.parent.BaseUri; } c = c.parent; break; } case XmlNodeType.Text: case XmlNodeType.SignificantWhitespace: case XmlNodeType.Whitespace: if ((baseUri != null && baseUri != uri) || (li != null && li.HasLineInfo())) { n = new XText(r.Value); } else { c.AddStringSkipNotify(r.Value); } break; case XmlNodeType.CDATA: n = new XCData(r.Value); break; case XmlNodeType.Comment: n = new XComment(r.Value); break; case XmlNodeType.ProcessingInstruction: n = new XProcessingInstruction(r.Name, r.Value); break; case XmlNodeType.DocumentType: n = new XDocumentType(r.LocalName, r.GetAttribute("PUBLIC"), r.GetAttribute("SYSTEM"), r.Value); break; case XmlNodeType.EntityReference: if (!r.CanResolveEntity) { throw new InvalidOperationException(SR.InvalidOperation_UnresolvedEntityReference); } r.ResolveEntity(); break; case XmlNodeType.EndEntity: break; default: throw new InvalidOperationException(SR.Format(SR.InvalidOperation_UnexpectedNodeType, r.NodeType)); } if (n != null) { if (baseUri != null && baseUri != uri) { n.SetBaseUri(uri); } if (li != null && li.HasLineInfo()) { n.SetLineInfo(li.LineNumber, li.LinePosition); } c.AddNodeSkipNotify(n); n = null; } } while (r.Read()); }
/// <summary> /// Invoked for each <see cref="XComment"/> /// </summary> /// <param name="comment"></param> public virtual void Visit(XComment comment) { Contract.Requires<ArgumentNullException>(comment != null); }
/// <summary> /// Validate enumeration of element descendents. /// </summary> /// <param name="contextValue"></param> /// <returns></returns> //[Variation(Desc = "ElementDescendents")] public void ElementDescendents() { 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.DescendantsAndSelf(), new XElement[] { level1, level2, level3 }); Validate.EnumeratorDeepEquals( level0.DescendantNodesAndSelf(), new XNode[] { level0, level1, level2, level3, comment }); Validate.EnumeratorDeepEquals( level0.DescendantsAndSelf(null), new XElement[0]); Validate.EnumeratorDeepEquals( level0.DescendantsAndSelf("Level1"), new XElement[] { level0, level1 }); }
public bool Equals(XNode x, XNode y) { if (x == null) { return(y == null); } else if (y == null) { return(false); } //throw new NotImplementedException (); if (x.NodeType != y.NodeType) { return(false); } switch (x.NodeType) { case XmlNodeType.Document: XDocument doc1 = (XDocument)x; XDocument doc2 = (XDocument)y; if (!Equals(doc1.Declaration, doc2.Declaration)) { return(false); } IEnumerator <XNode> id2 = doc2.Nodes().GetEnumerator(); foreach (XNode n in doc1.Nodes()) { if (!id2.MoveNext()) { return(false); } if (!Equals(n, id2.Current)) { return(false); } } return(!id2.MoveNext()); case XmlNodeType.Element: XElement e1 = (XElement)x; XElement e2 = (XElement)y; if (e1.Name != e2.Name) { return(false); } IEnumerator <XAttribute> ia2 = e2.Attributes().GetEnumerator(); foreach (XAttribute n in e1.Attributes()) { if (!ia2.MoveNext()) { return(false); } if (!Equals(n, ia2.Current)) { return(false); } } if (ia2.MoveNext()) { return(false); } IEnumerator <XNode> ie2 = e2.Nodes().GetEnumerator(); foreach (XNode n in e1.Nodes()) { if (!ie2.MoveNext()) { return(false); } if (!Equals(n, ie2.Current)) { return(false); } } return(!ie2.MoveNext()); case XmlNodeType.Comment: XComment c1 = (XComment)x; XComment c2 = (XComment)y; return(c1.Value == c2.Value); case XmlNodeType.ProcessingInstruction: XPI p1 = (XPI)x; XPI p2 = (XPI)y; return(p1.Target == p2.Target && p1.Data == p2.Data); case XmlNodeType.DocumentType: XDocumentType d1 = (XDocumentType)x; XDocumentType d2 = (XDocumentType)y; return(d1.Name == d2.Name && d1.PublicId == d2.PublicId && d1.SystemId == d2.SystemId && d1.InternalSubset == d2.InternalSubset); case XmlNodeType.Text: return(((XText)x).Value == ((XText)y).Value); } throw new Exception("INTERNAL ERROR: should not happen"); }
internal void ReadContentFrom(XmlReader r, LoadOptions o) { if ((o & (LoadOptions.SetLineInfo | LoadOptions.SetBaseUri)) == LoadOptions.None) { this.ReadContentFrom(r); } else { if (r.ReadState != System.Xml.ReadState.Interactive) { throw new InvalidOperationException(System.Xml.Linq.Res.GetString("InvalidOperation_ExpectedInteractive")); } XContainer parent = this; XNode n = null; NamespaceCache cache = new NamespaceCache(); NamespaceCache cache2 = new NamespaceCache(); string baseUri = ((o & LoadOptions.SetBaseUri) != LoadOptions.None) ? r.BaseURI : null; IXmlLineInfo info = ((o & LoadOptions.SetLineInfo) != LoadOptions.None) ? (r as IXmlLineInfo) : null; do { string baseURI = r.BaseURI; switch (r.NodeType) { case XmlNodeType.Element: { XElement element = new XElement(cache.Get(r.NamespaceURI).GetName(r.LocalName)); if ((baseUri != null) && (baseUri != baseURI)) { element.SetBaseUri(baseURI); } if ((info != null) && info.HasLineInfo()) { element.SetLineInfo(info.LineNumber, info.LinePosition); } if (r.MoveToFirstAttribute()) { do { XAttribute a = new XAttribute(cache2.Get((r.Prefix.Length == 0) ? string.Empty : r.NamespaceURI).GetName(r.LocalName), r.Value); if ((info != null) && info.HasLineInfo()) { a.SetLineInfo(info.LineNumber, info.LinePosition); } element.AppendAttributeSkipNotify(a); }while (r.MoveToNextAttribute()); r.MoveToElement(); } parent.AddNodeSkipNotify(element); if (!r.IsEmptyElement) { parent = element; if (baseUri != null) { baseUri = baseURI; } } break; } case XmlNodeType.Text: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: if (((baseUri == null) || (baseUri == baseURI)) && ((info == null) || !info.HasLineInfo())) { parent.AddStringSkipNotify(r.Value); } else { n = new XText(r.Value); } break; case XmlNodeType.CDATA: n = new XCData(r.Value); break; case XmlNodeType.EntityReference: if (!r.CanResolveEntity) { throw new InvalidOperationException(System.Xml.Linq.Res.GetString("InvalidOperation_UnresolvedEntityReference")); } r.ResolveEntity(); break; case XmlNodeType.ProcessingInstruction: n = new XProcessingInstruction(r.Name, r.Value); break; case XmlNodeType.Comment: n = new XComment(r.Value); break; case XmlNodeType.DocumentType: n = new XDocumentType(r.LocalName, r.GetAttribute("PUBLIC"), r.GetAttribute("SYSTEM"), r.Value, r.DtdInfo); break; case XmlNodeType.EndElement: { if (parent.content == null) { parent.content = string.Empty; } XElement element2 = parent as XElement; if (((element2 != null) && (info != null)) && info.HasLineInfo()) { element2.SetEndElementLineInfo(info.LineNumber, info.LinePosition); } if (parent == this) { return; } if ((baseUri != null) && parent.HasBaseUri) { baseUri = parent.parent.BaseUri; } parent = parent.parent; break; } case XmlNodeType.EndEntity: break; default: throw new InvalidOperationException(System.Xml.Linq.Res.GetString("InvalidOperation_UnexpectedNodeType", new object[] { r.NodeType })); } if (n != null) { if ((baseUri != null) && (baseUri != baseURI)) { n.SetBaseUri(baseURI); } if ((info != null) && info.HasLineInfo()) { n.SetLineInfo(info.LineNumber, info.LinePosition); } parent.AddNodeSkipNotify(n); n = null; } }while (r.Read()); } }
internal override bool DeepEquals(XNode node) { XComment comment = node as XComment; return((comment != null) && (this.value == comment.value)); }
public bool ReadContentFrom(XContainer rootContainer, XmlReader r, LoadOptions o) { XNode newNode = null; string baseUri = r.BaseURI; switch (r.NodeType) { case XmlNodeType.Element: { XElement e = new XElement(_eCache.Get(r.NamespaceURI).GetName(r.LocalName)); if (_baseUri != null && _baseUri != baseUri) { e.SetBaseUri(baseUri); } if (_lineInfo != null && _lineInfo.HasLineInfo()) { e.SetLineInfo(_lineInfo.LineNumber, _lineInfo.LinePosition); } if (r.MoveToFirstAttribute()) { do { XAttribute a = new XAttribute(_aCache.Get(r.Prefix.Length == 0 ? string.Empty : r.NamespaceURI).GetName(r.LocalName), r.Value); if (_lineInfo != null && _lineInfo.HasLineInfo()) { a.SetLineInfo(_lineInfo.LineNumber, _lineInfo.LinePosition); } e.AppendAttributeSkipNotify(a); } while (r.MoveToNextAttribute()); r.MoveToElement(); } _currentContainer.AddNodeSkipNotify(e); if (!r.IsEmptyElement) { _currentContainer = e; if (_baseUri != null) { _baseUri = baseUri; } } break; } case XmlNodeType.EndElement: { if (_currentContainer.content == null) { _currentContainer.content = string.Empty; } // Store the line info of the end element tag. // Note that since we've got EndElement the current container must be an XElement XElement e = _currentContainer as XElement; Debug.Assert(e != null, "EndElement received but the current container is not an element."); if (e != null && _lineInfo != null && _lineInfo.HasLineInfo()) { e.SetEndElementLineInfo(_lineInfo.LineNumber, _lineInfo.LinePosition); } if (_currentContainer == rootContainer) { return(false); } if (_baseUri != null && _currentContainer.HasBaseUri) { _baseUri = _currentContainer.parent.BaseUri; } _currentContainer = _currentContainer.parent; break; } case XmlNodeType.Text: case XmlNodeType.SignificantWhitespace: case XmlNodeType.Whitespace: if ((_baseUri != null && _baseUri != baseUri) || (_lineInfo != null && _lineInfo.HasLineInfo())) { newNode = new XText(r.Value); } else { _currentContainer.AddStringSkipNotify(r.Value); } break; case XmlNodeType.CDATA: newNode = new XCData(r.Value); break; case XmlNodeType.Comment: newNode = new XComment(r.Value); break; case XmlNodeType.ProcessingInstruction: newNode = new XProcessingInstruction(r.Name, r.Value); break; case XmlNodeType.DocumentType: newNode = new XDocumentType(r.LocalName, r.GetAttribute("PUBLIC"), r.GetAttribute("SYSTEM"), r.Value); break; case XmlNodeType.EntityReference: if (!r.CanResolveEntity) { throw new InvalidOperationException(SR.InvalidOperation_UnresolvedEntityReference); } r.ResolveEntity(); break; case XmlNodeType.EndEntity: break; default: throw new InvalidOperationException(SR.Format(SR.InvalidOperation_UnexpectedNodeType, r.NodeType)); } if (newNode != null) { if (_baseUri != null && _baseUri != baseUri) { newNode.SetBaseUri(baseUri); } if (_lineInfo != null && _lineInfo.HasLineInfo()) { newNode.SetLineInfo(_lineInfo.LineNumber, _lineInfo.LinePosition); } _currentContainer.AddNodeSkipNotify(newNode); newNode = null; } return(true); }
/// <summary> /// Initializes a new comment node from an existing comment node. /// </summary> /// <param name="other">Comment node to copy from.</param> public XComment(XComment other) { ArgumentNullException.ThrowIfNull(other); this.value = other.value; }
public XCommentWrapper(XComment text) : base(text) { }
internal override bool DeepEquals(XNode node) { XComment other = node as XComment; return(other != null && value == other.value); }