//</Snippet5> //************************************************************************************ // // Add an element to the XML document at a specific location // Takes a string that describes where the user wants the new node // to be positioned. The string comes from a series of radio buttons in a UI. // this method also accepts the XMLDocument in context. You have to use the // this instance because it is the object that was used to generate the // selectedBook XMLNode. // //************************************************************************************ //</Snipppet9> public void InsertBookElement(XmlElement bookElement, string position, XmlNode selectedBook, bool validateNode, bool generateSchema) { XmlDocument doc = bookElement.OwnerDocument; string stringThatContainsNewline = bookElement.OuterXml; switch (position) { case Constants.positionTop: // Add newline characters and spaces to make XML more readable. XmlSignificantWhitespace sigWhiteSpace = doc.CreateSignificantWhitespace("\n "); doc.DocumentElement.InsertBefore(sigWhiteSpace, doc.DocumentElement.FirstChild); doc.DocumentElement.InsertAfter(bookElement, doc.DocumentElement.FirstChild); break; case Constants.positionBottom: // Add newline characters to make XML more readable. XmlWhitespace whitespace = doc.CreateWhitespace(" "); XmlNode appendedNode = doc.DocumentElement.AppendChild(bookElement); doc.DocumentElement.InsertBefore(whitespace, appendedNode); sigWhiteSpace = doc.CreateSignificantWhitespace("\n"); doc.DocumentElement.InsertAfter(sigWhiteSpace, appendedNode); break; case Constants.positionAbove: // Add newline characters to make XML more readable. XmlNode currNode = doc.DocumentElement.InsertBefore(bookElement, selectedBook); sigWhiteSpace = doc.CreateSignificantWhitespace("\n "); doc.DocumentElement.InsertAfter(sigWhiteSpace, currNode); break; case Constants.positionBelow: // Add newline characters to make XML more readable. sigWhiteSpace = doc.CreateSignificantWhitespace("\n "); XmlNode whiteSpaceNode = doc.DocumentElement.InsertAfter(sigWhiteSpace, selectedBook); doc.DocumentElement.InsertAfter(bookElement, whiteSpaceNode); break; default: doc.DocumentElement.AppendChild(bookElement); break; } if (validateNode) { validateXML(generateSchema, doc); } }
private static XmlNode CreateNode(XmlDocument doc, XmlNodeType nodeType) { Assert.NotNull(doc); switch (nodeType) { case XmlNodeType.CDATA: return(doc.CreateCDataSection(@"< & <tag> < ! > & </tag> ")); case XmlNodeType.Comment: return(doc.CreateComment(@"comment")); case XmlNodeType.Element: return(doc.CreateElement("E")); case XmlNodeType.Text: return(doc.CreateTextNode("text")); case XmlNodeType.Whitespace: return(doc.CreateWhitespace(@" ")); case XmlNodeType.SignificantWhitespace: return(doc.CreateSignificantWhitespace(" ")); default: Assert.True(false, "Wrong XmlNodeType: '" + nodeType + "'"); return(null); } }
public Sample() { XmlDocument doc = new XmlDocument(); doc.LoadXml("<!-- Sample XML fragment -->" + "<author xml:space='preserve'>" + "<first-name>Eva</first-name>" + "<last-name>Corets</last-name>" + "</author>"); Console.WriteLine("InnerText before..."); Console.WriteLine(doc.DocumentElement.InnerText); // Add white space. currNode = doc.DocumentElement; XmlSignificantWhitespace sigws = doc.CreateSignificantWhitespace("\t"); currNode.InsertAfter(sigws, currNode.FirstChild); Console.WriteLine(); Console.WriteLine("InnerText after..."); Console.WriteLine(doc.DocumentElement.InnerText); // Save and then display the file. doc.Save(filename); Console.WriteLine(); Console.WriteLine("Reading file..."); ReadFile(filename); }
private async Task Dump_Out_XML() { Debug.WriteLine("Debugging Dump..."); XmlDocument outputXML = new XmlDocument(); XmlElement rootElement = outputXML.CreateElement(string.Empty, "stations", string.Empty); outputXML.AppendChild(rootElement); XmlSignificantWhitespace sigws = outputXML.CreateSignificantWhitespace("\n\t"); rootElement.InsertAfter(sigws, rootElement.FirstChild); foreach (Podcast thisOne in PodList.Items) { XmlElement stationElement = outputXML.CreateElement(string.Empty, "station", string.Empty); XmlElement stationNameElement = outputXML.CreateElement(string.Empty, "stationName", string.Empty); XmlText text1 = outputXML.CreateTextNode(thisOne.stationName); stationNameElement.AppendChild(text1); stationElement.AppendChild(stationNameElement); stationElement.InsertAfter(sigws, stationNameElement); XmlElement stationURLElement = outputXML.CreateElement(string.Empty, "stationURL", string.Empty); XmlText text2 = outputXML.CreateTextNode(thisOne.stationURL); stationURLElement.AppendChild(text2); stationElement.AppendChild(stationURLElement); stationElement.InsertAfter(sigws, stationURLElement); rootElement.AppendChild(stationElement); Debug.WriteLine(thisOne.stationName); Debug.WriteLine(thisOne.stationURL); } Debug.WriteLine(outputXML.InnerXml.ToString()); StorageFolder PodBlasterFolder = await KnownFolders.MusicLibrary.GetFolderAsync("Podblaster"); string XMLFilePath = PodBlasterFolder.Path + @"\stations.xml"; StorageFile XMLFile = await PodBlasterFolder.GetFileAsync("stations.xml"); await FileIO.WriteTextAsync(XMLFile, outputXML.InnerXml.ToString()); Debug.WriteLine("Wrote out XML File!"); }
public void XmlSignificantWhitespaceBadConstructor() { try { broken = document.CreateSignificantWhitespace("black"); } catch (ArgumentException) { return; } catch (Exception) { Assert.Fail("Incorrect Exception thrown."); } }
private void ProcessAppInfoDocMarkup(bool root) { //First time reader is positioned on AppInfo or Documentation element XmlNode currentNode = null; switch (reader.NodeType) { case XmlNodeType.Element: annotationNSManager.PushScope(); currentNode = LoadElementNode(root); break; case XmlNodeType.Text: currentNode = dummyDocument.CreateTextNode(reader.Value); goto default; case XmlNodeType.SignificantWhitespace: currentNode = dummyDocument.CreateSignificantWhitespace(reader.Value); goto default; case XmlNodeType.CDATA: currentNode = dummyDocument.CreateCDataSection(reader.Value); goto default; case XmlNodeType.EntityReference: currentNode = dummyDocument.CreateEntityReference(reader.Name); goto default; case XmlNodeType.Comment: currentNode = dummyDocument.CreateComment(reader.Value); goto default; case XmlNodeType.ProcessingInstruction: currentNode = dummyDocument.CreateProcessingInstruction(reader.Name, reader.Value); goto default; case XmlNodeType.EndEntity: break; case XmlNodeType.Whitespace: break; case XmlNodeType.EndElement: annotationNSManager.PopScope(); parentNode = parentNode.ParentNode; break; default: //other possible node types: Document/DocType/DocumentFrag/Entity/Notation/Xmldecl cannot appear as children of xs:appInfo or xs:doc Debug.Assert(currentNode != null); Debug.Assert(parentNode != null); parentNode.AppendChild(currentNode); break; } }
public void GetReady() { document = new XmlDocument(); document.LoadXml("<root><foo></foo></root>"); XmlElement element = document.CreateElement("foo"); whitespace = document.CreateSignificantWhitespace("\r\n"); element.AppendChild(whitespace); doc2 = new XmlDocument(); }
//[Fact] https://github.com/dotnet/corefx/issues/208 public static void ImportSignificantWhitespace() { var whitespace = " \t"; var tempDoc = new XmlDocument(); var nodeToImport = tempDoc.CreateSignificantWhitespace(whitespace); var xmlDocument = new XmlDocument(); var node = xmlDocument.ImportNode(nodeToImport, true); Assert.Equal(xmlDocument, node.OwnerDocument); Assert.Equal(XmlNodeType.SignificantWhitespace, node.NodeType); Assert.Equal(whitespace, node.Value); }
public static void ImportSignificantWhitespace() { var whitespace = " \t"; var tempDoc = new XmlDocument(); var nodeToImport = tempDoc.CreateSignificantWhitespace(whitespace); var xmlDocument = new XmlDocument(); var node = xmlDocument.ImportNode(nodeToImport, true); Assert.Equal(xmlDocument, node.OwnerDocument); Assert.Equal(XmlNodeType.SignificantWhitespace, node.NodeType); Assert.Equal(whitespace, node.Value); }
private void button1_Click(object sender, EventArgs e) { string path = Application.StartupPath + @"\sample.xml"; XmlDocument doc = new XmlDocument(); XmlElement root = doc.CreateElement("root"); XmlElement fullname = doc.CreateElement("fullname"); XmlElement address = doc.CreateElement("address"); XmlText fullnametext = doc.CreateTextNode(textBox1.Text); XmlText street1 = doc.CreateTextNode(textBox2.Text); XmlText street2 = doc.CreateTextNode(textBox3.Text); XmlText city = doc.CreateTextNode(textBox4.Text); XmlText state = doc.CreateTextNode(textBox5.Text); XmlText country = doc.CreateTextNode(textBox6.Text); XmlSignificantWhitespace sws1 = doc.CreateSignificantWhitespace("\r\n"); XmlSignificantWhitespace sws2 = doc.CreateSignificantWhitespace("\r\n"); XmlSignificantWhitespace sws3 = doc.CreateSignificantWhitespace("\r\n"); XmlSignificantWhitespace sws4 = doc.CreateSignificantWhitespace("\r\n"); XmlSignificantWhitespace sws5 = doc.CreateSignificantWhitespace("\r\n"); fullname.AppendChild(fullnametext); address.AppendChild(street1); address.AppendChild(sws1); address.AppendChild(street2); address.AppendChild(sws2); address.AppendChild(city); address.AppendChild(sws3); address.AppendChild(state); address.AppendChild(sws4); address.AppendChild(country); address.AppendChild(sws5); doc.AppendChild(root); root.AppendChild(fullname); root.AppendChild(address); doc.Save(path); }
public void AsText_on_significant_whitespace_should_return_value() { var document = new XmlDocument(); document.AppendChild(document.CreateElement("test")); var x = document.CreateElement("x"); document.DocumentElement.AppendChild(x); x.AppendChild(document.CreateSignificantWhitespace(" ")); var doc = new XDoc(document); Assert.AreEqual(" ", doc["x"][0].AsText); }
// Test the construction of whitespace nodes. public void TestXmlSignificantWhitespaceConstruct() { // Valid significant whitespace strings. CheckProperties("Construct (1)", doc.CreateSignificantWhitespace(null), String.Empty, false); CheckProperties("Construct (2)", doc.CreateSignificantWhitespace(String.Empty), String.Empty, false); CheckProperties("Construct (3)", doc.CreateSignificantWhitespace(" \f\t\r\n\v"), " \f\t\r\n\v", false); // Invalid significant whitespace strings. try { doc.CreateWhitespace("abc"); Fail("Construct (4)"); } catch (ArgumentException) { // Success } }
// Test setting attributes via direct text node inserts. public void TestXmlAttributeInsert() { XmlAttribute attr; attr = doc.CreateAttribute("prefix", "foo", "uri"); XmlText text1 = doc.CreateTextNode("hello"); XmlText text2 = doc.CreateTextNode(" and goodbye"); attr.AppendChild(text1); AssertEquals("Insert (1)", "hello", attr.Value); AssertEquals("Insert (2)", text1, attr.FirstChild); AssertEquals("Insert (3)", text1, attr.LastChild); attr.AppendChild(text2); AssertEquals("Insert (4)", "hello and goodbye", attr.Value); AssertEquals("Insert (5)", text1, attr.FirstChild); AssertEquals("Insert (6)", text2, attr.LastChild); // Entity references do not affect the combined value, // but they do affect the XML. XmlEntityReference entity = doc.CreateEntityReference("foo"); attr.AppendChild(entity); AssertEquals("Insert (7)", "hello and goodbye", attr.Value); AssertEquals("Insert (8)", "hello and goodbye&foo;", attr.InnerXml); // Cannot insert whitespace into attributes. try { attr.AppendChild(doc.CreateWhitespace(" ")); Fail("Insert (9)"); } catch (InvalidOperationException) { // Success } try { attr.AppendChild(doc.CreateSignificantWhitespace(" ")); Fail("Insert (9)"); } catch (InvalidOperationException) { // Success } }
public void AsText_on_element_concats_whitespace_text_significant_whitespace_and_CDATA() { var document = new XmlDocument(); document.AppendChild(document.CreateElement("test")); var x = document.CreateElement("x"); document.DocumentElement.AppendChild(x); x.AppendChild(document.CreateTextNode("foo")); x.AppendChild(document.CreateWhitespace(" ")); x.AppendChild(document.CreateCDataSection("bar")); x.AppendChild(document.CreateSignificantWhitespace(" ")); var doc = new XDoc(document); Assert.AreEqual("foo bar ", doc["x"].AsText); }
public void SignificantWhitespaceIgnored2() { // To make sure, create pure significant whitespace element // using XmlNodeReader (that does not have xml:space attribute // column). DataSet ds = new DataSet(); XmlDocument doc = new XmlDocument(); doc.AppendChild(doc.CreateElement("root")); doc.DocumentElement.AppendChild(doc.CreateSignificantWhitespace (" \n\n")); XmlReader xr = new XmlNodeReader(doc); ds.InferXmlSchema(xr, null); DataSetAssertion.AssertDataSet("pure_whitespace", ds, "root", 0, 0); }
public static void Main() { XmlDocument doc = new XmlDocument(); doc.LoadXml("<author xml:space='preserve'>" + "<first-name>Eva</first-name>" + "<last-name>Corets</last-name>" + "</author>"); Console.WriteLine("InnerText before..."); Console.WriteLine(doc.DocumentElement.InnerText); // Add white space. XmlNode currNode = doc.DocumentElement; XmlSignificantWhitespace sigws = doc.CreateSignificantWhitespace("\t"); currNode.InsertAfter(sigws, currNode.FirstChild); Console.WriteLine(); Console.WriteLine("InnerText after..."); Console.WriteLine(doc.DocumentElement.InnerText); }
public static XmlNode CreateNode(XmlDocument doc, XmlNodeType nodeType) { Assert.NotNull(doc); switch (nodeType) { case XmlNodeType.CDATA: return doc.CreateCDataSection(@"< & <tag> < ! > & </tag> "); case XmlNodeType.Comment: return doc.CreateComment(@"comment"); case XmlNodeType.Element: return doc.CreateElement("E"); case XmlNodeType.Text: return doc.CreateTextNode("text"); case XmlNodeType.Whitespace: return doc.CreateWhitespace(@" "); case XmlNodeType.SignificantWhitespace: return doc.CreateSignificantWhitespace(" "); default: throw new ArgumentException("Wrong XmlNodeType: '" + nodeType + "'"); } }
public void InnerAndOuterXml() { whitespace = doc2.CreateSignificantWhitespace("\r\n\t "); Assert.AreEqual(String.Empty, whitespace.InnerXml); Assert.AreEqual("\r\n\t ", whitespace.OuterXml); }
protected override void projectItemGenerator_ProjectItemGenerated(object sender, ProjectItemGeneratedEventArgs e) { var name = e.ProjectItemName; if (name.StartsWith(Path.DirectorySeparatorChar)) { name = name.Substring(1, name.Length - 1); } var pathsRelative = new List <string>(); var paths = new List <string>(); paths.AddRange(_outputFolder.Split(Path.DirectorySeparatorChar)); paths.AddRange(e.ProjectName.Split(Path.DirectorySeparatorChar)); if (!e.ParentItemName.IsEmpty() && !e.ParentItemName.Contains(".")) { paths.AddRange(e.ParentItemName.Split(Path.DirectorySeparatorChar)); pathsRelative.AddRange(e.ParentItemName.Split(Path.DirectorySeparatorChar)); } else if (!e.ParentItemName.IsEmpty() && e.ParentItemName.Contains(".")) { var arr = e.ParentItemName.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries).ToList(); if (arr.Count > 1) { arr.RemoveAt(arr.Count - 1); paths.AddRange(arr); pathsRelative.AddRange(arr); } } paths.AddRange(name.Split(Path.DirectorySeparatorChar)); pathsRelative.AddRange(name.Split(Path.DirectorySeparatorChar)); var fileName = System.IO.Path.Combine(paths.ToArray()); //On linux the pasrsing of an absolute path will leave the first element of "paths" as empty string //Prepend file with path separator to signify absolute path if (paths.Any() && paths.FirstOrDefault() == string.Empty && !fileName.StartsWith(Path.DirectorySeparatorChar)) { fileName = Path.DirectorySeparatorChar + fileName; } var fileStateInfo = new Generator.Common.Util.FileStateInfo { FileName = fileName }; if (!File.Exists(fileName) || e.Overwrite) { var folderName = new FileInfo(fileName).DirectoryName; //In case this is a parent nested file, do not try to create if (!File.Exists(folderName)) { Directory.CreateDirectory(folderName); File.WriteAllText(fileName, e.ProjectItemContent); } else { fileName = System.IO.Path.Combine(_outputFolder, e.ProjectName, name); File.WriteAllText(fileName, e.ProjectItemContent); } } else { fileStateInfo.FileState = Generator.Common.Util.FileStateConstants.Skipped; } //Embed the file in the project if need be if (e.Properties.ContainsKey("BuildAction") && (int)e.Properties["BuildAction"] == 3) { var projectFileName = System.IO.Path.Combine(_outputFolder, e.ProjectName, $"{e.ProjectName}.csproj"); if (File.Exists(projectFileName)) { var includeFile = System.IO.Path.Combine(pathsRelative.ToArray()); var document = new XmlDocument(); document.PreserveWhitespace = true; document.Load(projectFileName); var groups = document.DocumentElement.SelectNodes("ItemGroup"); //Ensure file is not already embedded var checkFile = includeFile.Replace("/", @"\"); //in case linux if (document.DocumentElement.SelectSingleNode($"ItemGroup/EmbeddedResource[@Include='{checkFile}']") == null) { var whiteSpace = " "; XmlNode targetGroup = null; foreach (XmlElement g in groups) { //Find the first "ItemGroup" with a "EmbeddedResource" item //This will be the one to which we add the new embedded file if (g.SelectSingleNode("EmbeddedResource") != null) { if (g.FirstChild.NodeType == XmlNodeType.Whitespace) { if (g.FirstChild.Value.Replace("\r", "").Replace("\n", "").Contains('\t')) { whiteSpace = "\t"; } } targetGroup = g; break; } } //If there is no group create a new one if (targetGroup == null) { targetGroup = document.DocumentElement.AppendChild(document.CreateElement("ItemGroup")); } //Add whitespace and the item targetGroup.AppendChild(document.CreateSignificantWhitespace(whiteSpace)); var node = targetGroup.AppendChild(document.CreateElement("EmbeddedResource")); var attr = node.Attributes.Append(document.CreateAttribute("Include")); attr.Value = checkFile; targetGroup.AppendChild(document.CreateSignificantWhitespace("\r\n" + whiteSpace)); document.Save(projectFileName); } } } //Write Log Generator.Common.Logging.nHydrateLog.LogInfo("Project Item Generated: {0}", e.ProjectItemName); e.FileState = fileStateInfo.FileState; e.FullName = fileStateInfo.FileName; this.OnProjectItemGenerated(sender, e); }
public CreatorIssuer _0005(string config) { //Discarded unreachable code: IL_0002 //IL_0003: Incompatible stack heights: 0 vs 1 return(new ValPropertyStruct(tagIssuer.CreateSignificantWhitespace(config))); }
void CopyNode(XmlDocument newDoc, XmlNode from, XmlNode toParent) { if (RemoveAll && from.NodeType != XmlNodeType.Element) { return; } XmlNode child = null; bool newLineNode = false; switch (from.NodeType) { case XmlNodeType.Element: newLineNode = true; if (RemoveNamespacesAndPrefixes) { child = newDoc.CreateElement(from.LocalName); } else { XmlElement e = from as XmlElement; child = newDoc.CreateElement(e.Prefix, e.LocalName, e.NamespaceURI); } break; case XmlNodeType.Attribute: { if (RemoveAttributes) { return; } XmlAttribute fromAttr = from as XmlAttribute; if (!fromAttr.Specified) { return; } XmlAttribute a; if (RemoveNamespacesAndPrefixes) { a = newDoc.CreateAttribute(fromAttr.LocalName); } else { a = newDoc.CreateAttribute(fromAttr.Prefix, fromAttr.LocalName, fromAttr.NamespaceURI); } toParent.Attributes.Append(a); CopyNodes(newDoc, from, a); return; } case XmlNodeType.CDATA: newLineNode = true; child = newDoc.CreateCDataSection((from as XmlCDataSection).Data); break; case XmlNodeType.Comment: if (RemoveWhiteSpace) { return; } newLineNode = true; child = newDoc.CreateComment((from as XmlComment).Data); break; case XmlNodeType.ProcessingInstruction: newLineNode = true; XmlProcessingInstruction pi = from as XmlProcessingInstruction; child = newDoc.CreateProcessingInstruction(pi.Target, pi.Data); break; case XmlNodeType.DocumentType: newLineNode = true; toParent.AppendChild(from.CloneNode(true)); return; case XmlNodeType.EntityReference: child = newDoc.CreateEntityReference((from as XmlEntityReference).Name); break; case XmlNodeType.SignificantWhitespace: if (RemoveWhiteSpace) { return; } child = newDoc.CreateSignificantWhitespace(from.Value); break; case XmlNodeType.Text: if (RemoveText) { return; } newLineNode = true; child = newDoc.CreateTextNode(from.Value); break; case XmlNodeType.Whitespace: if (RemoveWhiteSpace) { return; } child = newDoc.CreateWhitespace(from.Value); break; case XmlNodeType.XmlDeclaration: newLineNode = true; XmlDeclaration d = from as XmlDeclaration; XmlDeclaration d1 = newDoc.CreateXmlDeclaration(d.Version, d.Encoding, d.Standalone); newDoc.InsertBefore(d1, newDoc.DocumentElement); return; } if (NewLines && newLineNode && toParent.NodeType != XmlNodeType.Attribute) { XmlSignificantWhitespace s = newDoc.CreateSignificantWhitespace("\r\n"); toParent.AppendChild(s); } toParent.AppendChild(child); CopyNodes(newDoc, from, child); }
private void MergeIntoDestination() { XmlNodeList nodes; var levenshtein = new NormalizedLevenshtein(); var root = _destDoc.DocumentElement; if (_replace) { nodes = root.SelectNodes("//xliff:trans-unit", _nsmgr); } else { nodes = root.SelectNodes("//xliff:trans-unit[not(xliff:target)]", _nsmgr); } foreach (XmlNode node in nodes) { var id = node.Attributes["id"].Value; if (_translations.ContainsKey(id)) { var source = node.SelectSingleNode("xliff:source", _nsmgr); var transSource = _translations[id].SelectSingleNode($"./xliff:source", _nsmgr); var transTarget = _translations[id].SelectSingleNode($"./xliff:target", _nsmgr); if (source.InnerText != transSource.InnerText) { var percentSimilar = Math.Round((1 - levenshtein.Distance(source.InnerText, transSource.InnerText)) * 100); if (_verbose) { Console.WriteLine($"Sources mismatch in id='{id}' Similarity {percentSimilar}%."); Console.WriteLine($" Source file='{transSource.InnerText}'"); Console.WriteLine($" Target file='{source.InnerText}'"); } if (percentSimilar < _fuzzy) { if (_verbose) { Console.WriteLine($"Skipping"); } continue; } } if (_replace) { var oldTarget = node.SelectSingleNode("xliff:target", _nsmgr); if (oldTarget != null) { node.RemoveChild(oldTarget); } } if (source.NextSibling.Name != "#significant-whitespace") { XmlSignificantWhitespace sigws = _destDoc.CreateSignificantWhitespace("\n "); node.InsertAfter(sigws, source); } XmlNode target = _destDoc.ImportNode(transTarget, true); node.InsertAfter(target, source.NextSibling); if (target.NextSibling.Name != "#significant-whitespace") { XmlSignificantWhitespace sigws = _destDoc.CreateSignificantWhitespace("\n "); node.InsertAfter(sigws, target); } } } }
/// <summary> /// Creates an System.Xml.XmlSignificantWhitespace node. /// </summary> /// <param name="text">The string must contain only the following characters #20; #10; #13; and #9;.</param> /// <returns>A new XmlSignificantWhitespace node.</returns> public XmlSignificantWhitespace CreateSignificantWhitespace(System.String text) { return(xmlDocument.CreateSignificantWhitespace(text)); }
private void LoadDocument() { bool preserveWhitespace = false; XmlReader r = this.reader; XmlNode parent = this.doc; XmlElement element; while (r.Read()) { XmlNode node = null; switch (r.NodeType) { case XmlNodeType.Element: bool fEmptyElement = r.IsEmptyElement; element = doc.CreateElement(r.Prefix, r.LocalName, r.NamespaceURI); AddToTable(element); element.IsEmpty = fEmptyElement; ReadAttributes(r, element); if (!fEmptyElement) { parent.AppendChild(element); parent = element; continue; } node = element; break; case XmlNodeType.EndElement: if (parent.ParentNode == null) { // syntax error in document. IXmlLineInfo li = (IXmlLineInfo)r; throw new XmlException(string.Format(SR.UnexpectedToken, "</" + r.LocalName + ">", li.LineNumber, li.LinePosition), null, li.LineNumber, li.LinePosition); } parent = parent.ParentNode; continue; case XmlNodeType.EntityReference: if (r.CanResolveEntity) { r.ResolveEntity(); } continue; case XmlNodeType.EndEntity: continue; case XmlNodeType.Attribute: node = LoadAttributeNode(); break; case XmlNodeType.Text: node = doc.CreateTextNode(r.Value); AddToTable(node); break; case XmlNodeType.SignificantWhitespace: node = doc.CreateSignificantWhitespace(r.Value); AddToTable(node); break; case XmlNodeType.Whitespace: if (preserveWhitespace) { node = doc.CreateWhitespace(r.Value); AddToTable(node); break; } else { continue; } case XmlNodeType.CDATA: node = doc.CreateCDataSection(r.Value); AddToTable(node); break; case XmlNodeType.XmlDeclaration: node = LoadDeclarationNode(); break; case XmlNodeType.ProcessingInstruction: node = doc.CreateProcessingInstruction(r.Name, r.Value); AddToTable(node); if (string.IsNullOrEmpty(this.xsltFileName) && r.Name == "xml-stylesheet") { string href = ParseXsltArgs(((XmlProcessingInstruction)node).Data); if (!string.IsNullOrEmpty(href)) { this.xsltFileName = href; } } break; case XmlNodeType.Comment: node = doc.CreateComment(r.Value); AddToTable(node); break; case XmlNodeType.DocumentType: { string pubid = r.GetAttribute("PUBLIC"); string sysid = r.GetAttribute("SYSTEM"); node = doc.CreateDocumentType(r.Name, pubid, sysid, r.Value); break; } default: UnexpectedNodeType(r.NodeType); break; } Debug.Assert(node != null); Debug.Assert(parent != null); if (parent != null) { parent.AppendChild(node); } } }
/// <summary> /// Creates, updates and inserts a node. /// </summary> private void InsertNode(XmlNode anchor, IUpdateOperation updateOperation) { // create node according to type XmlNode newXmlNode; switch (GetNodeType()) { case XmlNodeType.Attribute: newXmlNode = XmlDocument.CreateAttribute(Name, Namespace ?? string.Empty); break; case XmlNodeType.Element: newXmlNode = XmlDocument.CreateElement(Name, Namespace ?? string.Empty); break; case XmlNodeType.CData: newXmlNode = XmlDocument.CreateCDataSection(string.Empty); break; case XmlNodeType.Comment: newXmlNode = XmlDocument.CreateComment(string.Empty); break; case XmlNodeType.SignificantWhitespace: newXmlNode = XmlDocument.CreateSignificantWhitespace(string.Empty); break; case XmlNodeType.Text: newXmlNode = XmlDocument.CreateTextNode(string.Empty); break; case XmlNodeType.Whitespace: newXmlNode = XmlDocument.CreateWhitespace(string.Empty); break; default: // should not happen throw new ArgumentOutOfRangeException(); } // update node with input updateOperation.Update(newXmlNode); // insert node relative to anchor if (newXmlNode is XmlAttribute) { var newXmlAttribute = (XmlAttribute)newXmlNode; switch (GetNodePosition()) { case XmlNodePosition.Append: case XmlNodePosition.After: if (anchor is XmlAttribute) { var xmlAttribute = (XmlAttribute)anchor; if (xmlAttribute.OwnerElement != null) { xmlAttribute.OwnerElement.Attributes.InsertAfter(newXmlAttribute, xmlAttribute); } } else if (anchor.Attributes != null) { anchor.Attributes.Append(newXmlAttribute); } break; case XmlNodePosition.Prepend: case XmlNodePosition.Before: if (anchor is XmlAttribute) { var xmlAttribute = (XmlAttribute)anchor; if (xmlAttribute.OwnerElement != null) { xmlAttribute.OwnerElement.Attributes.InsertBefore(newXmlAttribute, xmlAttribute); } } else if (anchor.Attributes != null) { anchor.Attributes.Prepend(newXmlAttribute); } break; default: // should not happen throw new ArgumentOutOfRangeException(); } } else { switch (GetNodePosition()) { case XmlNodePosition.Append: anchor.AppendChild(newXmlNode); break; case XmlNodePosition.Prepend: anchor.PrependChild(newXmlNode); break; case XmlNodePosition.After: if (anchor.ParentNode != null) { anchor.ParentNode.InsertAfter(newXmlNode, anchor); } break; case XmlNodePosition.Before: if (anchor.ParentNode != null) { anchor.ParentNode.InsertBefore(newXmlNode, anchor); } break; default: // should not happen throw new ArgumentOutOfRangeException(); } } }
private XmlNode LoadNode(bool skipOverWhitespace) { XmlReader r = _reader; XmlNode parent = null; XmlElement element; IXmlSchemaInfo schemaInfo; do { XmlNode node = null; switch (r.NodeType) { case XmlNodeType.Element: bool fEmptyElement = r.IsEmptyElement; element = _doc.CreateElement(r.Prefix, r.LocalName, r.NamespaceURI); element.IsEmpty = fEmptyElement; if (r.MoveToFirstAttribute()) { XmlAttributeCollection attributes = element.Attributes; do { XmlAttribute attr = LoadAttributeNode(); attributes.Append(attr); // special case for load }while (r.MoveToNextAttribute()); r.MoveToElement(); } // recursively load all children. if (!fEmptyElement) { if (parent != null) { parent.AppendChildForLoad(element, _doc); } parent = element; continue; } else { schemaInfo = r.SchemaInfo; if (schemaInfo != null) { element.XmlName = _doc.AddXmlName(element.Prefix, element.LocalName, element.NamespaceURI, schemaInfo); } node = element; break; } case XmlNodeType.EndElement: if (parent == null) { return(null); } Debug.Assert(parent.NodeType == XmlNodeType.Element); schemaInfo = r.SchemaInfo; if (schemaInfo != null) { element = parent as XmlElement; if (element != null) { element.XmlName = _doc.AddXmlName(element.Prefix, element.LocalName, element.NamespaceURI, schemaInfo); } } if (parent.ParentNode == null) { return(parent); } parent = parent.ParentNode; continue; case XmlNodeType.EntityReference: node = LoadEntityReferenceNode(false); break; case XmlNodeType.EndEntity: Debug.Assert(parent == null); return(null); case XmlNodeType.Attribute: node = LoadAttributeNode(); break; case XmlNodeType.Text: node = _doc.CreateTextNode(r.Value); break; case XmlNodeType.SignificantWhitespace: node = _doc.CreateSignificantWhitespace(r.Value); break; case XmlNodeType.Whitespace: if (_preserveWhitespace) { node = _doc.CreateWhitespace(r.Value); break; } else if (parent == null && !skipOverWhitespace) { // if called from LoadEntityReferenceNode, just return null return(null); } else { continue; } case XmlNodeType.CDATA: node = _doc.CreateCDataSection(r.Value); break; case XmlNodeType.XmlDeclaration: node = LoadDeclarationNode(); break; case XmlNodeType.ProcessingInstruction: node = _doc.CreateProcessingInstruction(r.Name, r.Value); break; case XmlNodeType.Comment: node = _doc.CreateComment(r.Value); break; case XmlNodeType.DocumentType: node = LoadDocumentTypeNode(); break; default: throw UnexpectedNodeType(r.NodeType); } Debug.Assert(node != null); if (parent != null) { parent.AppendChildForLoad(node, _doc); } else { return(node); } }while (r.Read()); // when the reader ended before full subtree is read, return whatever we have created so far if (parent != null) { while (parent.ParentNode != null) { parent = parent.ParentNode; } } return(parent); }
private void ProcessAppInfoDocMarkup(bool root) { //First time reader is positioned on AppInfo or Documentation element XmlNode currentNode = null; switch (_reader.NodeType) { case XmlNodeType.Element: _annotationNSManager.PushScope(); currentNode = LoadElementNode(root); // Dev10 (TFS) #479761: The following code was to address the issue of where an in-scope namespace delaration attribute // was not added when an element follows an empty element. This fix will result in persisting schema in a consistent form // although it does not change the semantic meaning of the schema. // Since it is as a breaking change and Dev10 needs to maintain the backward compatibility, this fix is being reverted. // if (reader.IsEmptyElement) { // annotationNSManager.PopScope(); // } break; case XmlNodeType.Text: currentNode = _dummyDocument.CreateTextNode(_reader.Value); goto default; case XmlNodeType.SignificantWhitespace: currentNode = _dummyDocument.CreateSignificantWhitespace(_reader.Value); goto default; case XmlNodeType.CDATA: currentNode = _dummyDocument.CreateCDataSection(_reader.Value); goto default; case XmlNodeType.EntityReference: currentNode = _dummyDocument.CreateEntityReference(_reader.Name); goto default; case XmlNodeType.Comment: currentNode = _dummyDocument.CreateComment(_reader.Value); goto default; case XmlNodeType.ProcessingInstruction: currentNode = _dummyDocument.CreateProcessingInstruction(_reader.Name, _reader.Value); goto default; case XmlNodeType.EndEntity: break; case XmlNodeType.Whitespace: break; case XmlNodeType.EndElement: _annotationNSManager.PopScope(); _parentNode = _parentNode.ParentNode; break; default: //other possible node types: Document/DocType/DocumentFrag/Entity/Notation/Xmldecl cannot appear as children of xs:appInfo or xs:doc Debug.Assert(currentNode != null); Debug.Assert(_parentNode != null); _parentNode.AppendChild(currentNode); break; } }
private static int Detokenize(Tuple <ArrayDiffKind, Token>[] tokens, int index, XmlElement current, XmlDocument doc) { for (; index < tokens.Length; ++index) { var token = tokens[index]; switch (token.Item1) { case ArrayDiffKind.Same: case ArrayDiffKind.Added: switch (token.Item2.Type) { case XmlNodeType.CDATA: if (current == null) { throw new ArgumentNullException("current"); } current.AppendChild(doc.CreateCDataSection(token.Item2.Value)); break; case XmlNodeType.Comment: if (current == null) { throw new ArgumentNullException("current"); } current.AppendChild(doc.CreateComment(token.Item2.Value)); break; case XmlNodeType.SignificantWhitespace: if (current == null) { throw new ArgumentNullException("current"); } current.AppendChild(doc.CreateSignificantWhitespace(token.Item2.Value)); break; case XmlNodeType.Text: if (current == null) { throw new ArgumentNullException("current"); } current.AppendChild(doc.CreateTextNode(token.Item2.Value)); break; case XmlNodeType.Whitespace: if (current == null) { throw new ArgumentNullException("current"); } current.AppendChild(doc.CreateWhitespace(token.Item2.Value)); break; case XmlNodeType.Element: XmlElement next = doc.CreateElement(token.Item2.Value); if (current == null) { doc.AppendChild(next); } else { current.AppendChild(next); } index = Detokenize(tokens, index + 1, next, doc); break; case XmlNodeType.Attribute: if (current == null) { throw new ArgumentNullException("current"); } string[] parts = token.Item2.Value.Split(new char[] { '=' }, 2); current.SetAttribute(parts[0], parts[1]); break; case XmlNodeType.EndElement: // nothing to do break; case XmlNodeType.None: if (current == null) { throw new ArgumentNullException("current"); } // ensure we're closing the intended element if (token.Item2.Value != current.Name) { throw new InvalidOperationException(string.Format("mismatched element ending; found </{0}>, expected </{1}>", token.Item2.Value, current.Name)); } // we're done with this sequence return(index); default: throw new InvalidOperationException("unhandled node type: " + token.Item2.Type); } break; case ArrayDiffKind.Removed: // ignore removed nodes break; default: throw new InvalidOperationException("invalid diff kind: " + token.Item1); } } if (current != null) { throw new InvalidOperationException("unexpected end of tokens"); } return(index); }
private void DeserializeValue( JsonReader reader, XmlDocument document, XmlNamespaceManager manager, string propertyName, XmlNode currentNode) { switch (propertyName) { case TextName: currentNode.AppendChild(document.CreateTextNode(reader.Value.ToString())); break; case CDataName: currentNode.AppendChild(document.CreateCDataSection(reader.Value.ToString())); break; case WhitespaceName: currentNode.AppendChild(document.CreateWhitespace(reader.Value.ToString())); break; case SignificantWhitespaceName: currentNode.AppendChild(document.CreateSignificantWhitespace(reader.Value.ToString())); break; default: // processing instructions and the xml declaration start with ? if (propertyName[0] == '?') { if (propertyName == DeclarationName) { string version = null; string encoding = null; string standalone = null; while (reader.Read() && reader.TokenType != JsonToken.EndObject) { switch (reader.Value.ToString()) { case "@version": reader.Read(); version = reader.Value.ToString(); break; case "@encoding": reader.Read(); encoding = reader.Value.ToString(); break; case "@standalone": reader.Read(); standalone = reader.Value.ToString(); break; default: throw new JsonSerializationException( "Unexpected property name encountered while deserializing XmlDeclaration: " + reader.Value); } } XmlDeclaration declaration = document.CreateXmlDeclaration(version, encoding, standalone); currentNode.AppendChild(declaration); } else { XmlProcessingInstruction instruction = document.CreateProcessingInstruction(propertyName.Substring(1), reader.Value.ToString()); currentNode.AppendChild(instruction); } } else { // deserialize xml element bool finishedAttributes = false; bool finishedElement = false; string elementPrefix = GetPrefix(propertyName); var attributeNameValues = new Dictionary <string, string>(); // a string token means the element only has a single text child if (reader.TokenType != JsonToken.String && reader.TokenType != JsonToken.Null && reader.TokenType != JsonToken.Boolean && reader.TokenType != JsonToken.Integer && reader.TokenType != JsonToken.Float && reader.TokenType != JsonToken.Date) { // read properties until first non-attribute is encountered while (!finishedAttributes && !finishedElement && reader.Read()) { switch (reader.TokenType) { case JsonToken.PropertyName: string attributeName = reader.Value.ToString(); if (attributeName[0] == '@') { attributeName = attributeName.Substring(1); reader.Read(); string attributeValue = reader.Value.ToString(); attributeNameValues.Add(attributeName, attributeValue); string namespacePrefix; if (IsNamespaceAttribute(attributeName, out namespacePrefix)) { manager.AddNamespace(namespacePrefix, attributeValue); } } else { finishedAttributes = true; } break; case JsonToken.EndObject: finishedElement = true; break; default: throw new JsonSerializationException( "Unexpected JsonToken: " + reader.TokenType); } } } // have to wait until attributes have been parsed before creating element // attributes may contain namespace info used by the element XmlElement element = (!string.IsNullOrEmpty(elementPrefix)) ? document.CreateElement(propertyName, manager.LookupNamespace(elementPrefix)) : document.CreateElement(propertyName); currentNode.AppendChild(element); // add attributes to newly created element foreach (KeyValuePair <string, string> nameValue in attributeNameValues) { string attributePrefix = GetPrefix(nameValue.Key); XmlAttribute attribute = (!string.IsNullOrEmpty(attributePrefix)) ? document.CreateAttribute(nameValue.Key, manager.LookupNamespace(attributePrefix)) : document.CreateAttribute(nameValue.Key); attribute.Value = nameValue.Value; element.SetAttributeNode(attribute); } if (reader.TokenType == JsonToken.String) { element.AppendChild(document.CreateTextNode(reader.Value.ToString())); } else if (reader.TokenType == JsonToken.Integer) { element.AppendChild(document.CreateTextNode(XmlConvert.ToString((long)reader.Value))); } else if (reader.TokenType == JsonToken.Float) { element.AppendChild(document.CreateTextNode(XmlConvert.ToString((double)reader.Value))); } else if (reader.TokenType == JsonToken.Boolean) { element.AppendChild(document.CreateTextNode(XmlConvert.ToString((bool)reader.Value))); } else if (reader.TokenType == JsonToken.Date) { element.AppendChild(document.CreateTextNode(XmlConvert.ToString((DateTime)reader.Value, DefaultDateTimeFormat))); } else if (reader.TokenType == JsonToken.Null) { // empty element. do nothing } else { // finished element will have no children to deserialize if (!finishedElement) { manager.PushScope(); DeserializeNode(reader, document, manager, element); manager.PopScope(); } } } break; } }
public XmlSignificantWhitespace CreateSignificantWhitespace(string text) { return(_doc.CreateSignificantWhitespace(text)); }
public IXmlNode CreateSignificantWhitespace(string text) { return(new XmlNodeWrapper(_document.CreateSignificantWhitespace(text))); }
private void LoadDocument() { bool preserveWhitespace = false; XmlReader r = this.reader; XmlNode parent = this.doc; XmlElement element; while (r.Read()) { XmlNode node = null; switch (r.NodeType) { case XmlNodeType.Element: bool fEmptyElement = r.IsEmptyElement; element = doc.CreateElement(r.Prefix, r.LocalName, r.NamespaceURI); AddToTable(element); element.IsEmpty = fEmptyElement; ReadAttributes(r, element); if (!fEmptyElement) { parent.AppendChild(element); parent = element; continue; } node = element; if (!namespaceList.Contains(node.NamespaceURI)) { namespaceList.Add(node.NamespaceURI); } break; case XmlNodeType.EndElement: if (parent.ParentNode == null) { // syntax error in document. IXmlLineInfo li = (IXmlLineInfo)r; throw new XmlException(string.Format("Unexpected end tag '{0}' at line {1} column {2}", r.LocalName, li.LineNumber, li.LinePosition), null, li.LineNumber, li.LinePosition); } parent = parent.ParentNode; continue; case XmlNodeType.EntityReference: if (r.CanResolveEntity) { r.ResolveEntity(); } continue; case XmlNodeType.EndEntity: continue; case XmlNodeType.Attribute: node = LoadAttributeNode(); if (!namespaceList.Contains(node.NamespaceURI)) { namespaceList.Add(node.NamespaceURI); } break; case XmlNodeType.Text: node = doc.CreateTextNode(r.Value); AddToTable(node); break; case XmlNodeType.SignificantWhitespace: node = doc.CreateSignificantWhitespace(r.Value); AddToTable(node); break; case XmlNodeType.Whitespace: if (preserveWhitespace) { node = doc.CreateWhitespace(r.Value); AddToTable(node); break; } else { continue; } case XmlNodeType.CDATA: node = doc.CreateCDataSection(r.Value); AddToTable(node); break; case XmlNodeType.XmlDeclaration: node = LoadDeclarationNode(); break; case XmlNodeType.ProcessingInstruction: node = doc.CreateProcessingInstruction(r.Name, r.Value); AddToTable(node); break; case XmlNodeType.Comment: node = doc.CreateComment(r.Value); AddToTable(node); break; case XmlNodeType.DocumentType: continue; default: UnexpectedNodeType(r.NodeType); break; } Debug.Assert(node != null); Debug.Assert(parent != null); if (parent != null) { parent.AppendChild(node); } } }