static void Main(string[] args) { var document = new XPathDocument("books.xml"); XPathNavigator navigator = document.CreateNavigator(); Console.WriteLine("Navigator is readonly. CanEdit = {0}", navigator.CanEdit); var xmldoc = new XmlDocument(); xmldoc.Load("books.xml"); navigator = xmldoc.CreateNavigator(); Console.WriteLine("Now you can edit navigator. CanEdit = {0}.", navigator.CanEdit); navigator.MoveToChild("ListOfBooks", ""); navigator.MoveToChild("Book", ""); navigator.InsertBefore("<InsertBefore>insert_before</InsertBefore>"); navigator.InsertAfter("<InsertAfter>insert_after</InsertAfter>"); navigator.AppendChild("<AppendChild>append_child</AppendChild>"); navigator.MoveToNext("Book", ""); navigator.InsertBefore("<InsertBefore>11111111</InsertBefore>"); navigator.InsertAfter("<InsertAfter>22222222</InsertAfter>"); navigator.AppendChild("<AppendChild>33333333</AppendChild>"); xmldoc.Save("books.xml"); Console.ReadKey(); }
void Success4(XPathNavigator nav, string xml) { nav.AppendChild(xml); nav.AppendChild(); nav.AppendChild(nav); nav.InsertAfter(xml); nav.InsertAfter(); nav.InsertAfter(nav); }
private HttpResponseMessage Operation(String SessionID) { XmlDocument myXml = new XmlDocument(); XPathNavigator xNav = myXml.CreateNavigator(); ReturnLogInformation InformationResult = TTCSLog.GetLogList(); List <InformationLogs> InformationList = (List <InformationLogs>)InformationResult.ReturnValue; XmlSerializer xmlSerializer = new XmlSerializer(typeof(InformationLogs[])); if (InformationList != null && InformationList.Count > 0) { using (var xs = xNav.AppendChild()) { xmlSerializer.Serialize(xs, InformationList.ToArray()); } return(new HttpResponseMessage() { Content = new StringContent(myXml.OuterXml, Encoding.UTF8, "text/xml") }); } else if (InformationList.Count == 0) { return(HostingHelper.ReturnError("There is no log information update. Please try again later.", myXml, xNav)); } else { return(HostingHelper.ReturnError(InformationResult.ReturnMessage, myXml, xNav)); } }
public string GeneratePrettyXml(SqlCommunicatorConnection connection) { XmlDocument xDoc = new XmlDocument(); // Set our output settings: XmlWriterSettings xmlSettings = new XmlWriterSettings(); xmlSettings.OmitXmlDeclaration = false; xmlSettings.Indent = true; xmlSettings.NewLineOnAttributes = true; if (connection != null) { XPathNavigator xNav = xDoc.CreateNavigator(); // Generate our Xml Document: using (XmlWriter xw = xNav.AppendChild()) { XmlSerializer xs = new XmlSerializer(connection.GetType()); xs.Serialize(xw, connection); } } return(xDoc.ToString()); }
private void writeInNewMember(string username, string password) { XmlWriterSettings xmlWriterSettings = new XmlWriterSettings(); xmlWriterSettings.Indent = true; xmlWriterSettings.NewLineOnAttributes = true; XmlDocument xmlDocument = new XmlDocument(); xmlDocument.Load(HttpContext.Current.Server.MapPath("App_Data/Member.xml")); // find the node XPathNavigator xPathNavigator = xmlDocument.CreateNavigator(); xPathNavigator.MoveToChild("Members", ""); XmlWriter xmlWriter = xPathNavigator.AppendChild(); xmlWriter.WriteStartElement("Member"); xmlWriter.WriteElementString("Username", username); xmlWriter.WriteElementString("Password", password); xmlWriter.WriteEndElement(); xmlWriter.Close(); xmlDocument.Save(HttpContext.Current.Server.MapPath("App_Data/Member.xml")); }
// empty content is allowed. public void AppendChildEmptyString() { XPathNavigator nav = GetInstance("<root/>"); nav.MoveToFirstChild(); // root nav.AppendChild(String.Empty); }
public XmlDocument SerializeToXmlDocument(T t) { //XmlSerializer ser = new XmlSerializer(typeof(T)); //XmlDocument xd = null; // //using (MemoryStream memStm = new MemoryStream()) //{ // ser.Serialize(memStm, t); // XmlReaderSettings settings = new XmlReaderSettings(); // settings.IgnoreWhitespace = true; // // using (var xtr = XmlReader.Create(memStm, settings)) // { // xd = new XmlDocument(); // xd.Load(xtr); // } //} XmlDocument doc = new XmlDocument(); XPathNavigator nav = doc.CreateNavigator(); using (XmlWriter w = nav.AppendChild()) { XmlSerializer ser = new XmlSerializer(typeof(T)); ser.Serialize(w, t); } return(doc); }
public override void WriteStartBlock(string language) { writer = location.AppendChild(); writer.WriteStartElement("div"); writer.WriteAttributeString("codeLanguage", language); position = 0; }
private void MergeResourses(XmlElement currentResources, XPathNavigator newResources) { Dictionary <string, Resource> currentItems = LoadResources(currentResources); Dictionary <string, Resource> newItems = LoadResources(newResources); XPathNavigator dataSet = currentResources.SelectSingleNode("NewDataSet").CreateNavigator(); foreach (KeyValuePair <string, Resource> newItem in newItems) { Resource current = null; Resource newResource = newItem.Value; if (currentItems.TryGetValue(newItem.Key, out current)) { // Already in source xml. Update the crucial if required, otherwise leave. if (current.Crucial != newResource.Crucial) { XmlElement crucial = (XmlElement)current.Element.SelectSingleNode("Crucial"); if (crucial != null) { crucial.InnerText = newResource.Crucial; } } } else { // Not currently in so add dataSet.AppendChild(newResource.Navigator); } } }
/// <summary> /// Updates the node replacing inheritdoc node with comments found. /// </summary> /// <param name="inheritDocNodeNavigator">Navigator for inheritdoc node</param> /// <param name="contentNodeNavigator">Navigator for content</param> private void UpdateNode(XPathNavigator inheritDocNodeNavigator, XPathNavigator contentNodeNavigator) { // retrieve the selection filter if specified. string selectValue = inheritDocNodeNavigator.GetAttribute("select", string.Empty); if (!string.IsNullOrEmpty(selectValue)) { sourceExpression = XPathExpression.Compile(selectValue); } inheritDocNodeNavigator.MoveToParent(); if (inheritDocNodeNavigator.LocalName != "comments" && inheritDocNodeNavigator.LocalName != "element") { sourceExpression = XPathExpression.Compile(inheritDocNodeNavigator.LocalName); } else { inheritDocNodeNavigator.MoveTo(this.sourceDocument.CreateNavigator().SelectSingleNode(inheritDocExpression)); } XPathNodeIterator sources = (XPathNodeIterator)contentNodeNavigator.CreateNavigator().Evaluate(sourceExpression); inheritDocNodeNavigator.DeleteSelf(); // append the source nodes to the target node foreach (XPathNavigator source in sources) { inheritDocNodeNavigator.AppendChild(source); } }
private XmlElement SerializeObjectToXML(XmlElement parent, object obj) { // TODO: Need to handle asset references // Because of runtime compability, always try to embed objects // If that fails, try to find references to assets (e.g. for textures) if (obj == null) { //Debug.LogWarning("Field value == null; Remember to give default values to node fields. "); return(null); } try { // Try to embed object XmlSerializer serializer = new XmlSerializer(obj.GetType()); XPathNavigator navigator = parent.CreateNavigator(); using (XmlWriter writer = navigator.AppendChild()) { writer.WriteWhitespace(""); serializer.Serialize(writer, obj); } return((XmlElement)parent.LastChild); } catch (Exception) { Debug.Log("Could not serialize " + obj.ToString()); return(null); } }
private void SaveSection4(string countiesCoverage, List <string[]> valuesArray) { try { XPathNavigator mainNav = this.MainDataSource.CreateNavigator(); XPathNavigator section4 = mainNav.SelectSingleNode("/my:myFields/my:Sec04_PropAreaOfCaverageOrg/my:sas_OrgCountyArea", NamespaceManager); XmlDocument doc = new XmlDocument(); XmlNode OrgCountyAreaCoverageElement = doc.CreateElement("OrgCountyAreaCoverage", NamespaceManager.LookupNamespace("my")); XmlNode fieldToAdd = doc.CreateElement("sas_CountiesCoverage", NamespaceManager.LookupNamespace("my")); XmlNode nodeToAdd = OrgCountyAreaCoverageElement.AppendChild(fieldToAdd); nodeToAdd.InnerText = countiesCoverage; fieldToAdd = doc.CreateElement("my:AreaCoverageAddition", NamespaceManager.LookupNamespace("my")); XmlNode areaCoverageAdditionElement = OrgCountyAreaCoverageElement.AppendChild(fieldToAdd); if (valuesArray.Count > 0) { foreach (string[] valueArray in valuesArray) { AddAreaCoverage(valueArray[0], valueArray[1], doc, areaCoverageAdditionElement, OrgCountyAreaCoverageElement); } } doc.AppendChild(OrgCountyAreaCoverageElement); section4.AppendChild(doc.DocumentElement.CreateNavigator()); } catch (Exception ex) { throw ex; } }
//===================================================================== /// <summary> /// Apply the copy command to the specified target document using the specified context /// </summary> /// <param name="targetDocument">The target document</param> /// <param name="context">The context to use</param> public override void Apply(XmlDocument targetDocument, IXmlNamespaceResolver context) { if (targetDocument == null) { throw new ArgumentNullException(nameof(targetDocument)); } // Extract the target node XPathExpression targetXPath = this.Target.Clone(); targetXPath.SetContext(context); XPathNavigator target = targetDocument.CreateNavigator().SelectSingleNode(targetXPath); if (target != null) { // Extract the source nodes XPathExpression sourceXPath = this.Source.Clone(); sourceXPath.SetContext(context); XPathNodeIterator sources = this.SourceDocument.CreateNavigator().Select(sourceXPath); // Append the source nodes to the target node foreach (XPathNavigator source in sources) { target.AppendChild(source); } // Don't warn or generate an error if no source nodes are found, that may be the case } else { this.ParentComponent.WriteMessage(MessageLevel.Error, "CopyFromFileCommand target node not found"); } }
private int Insert(IEntity entity, XPathNavigator nav) { //XPathNavigator nav = GetDocNodeById(entity); //XmlDocument doc = new XmlDocument(); //doc.Load(DbProvider.ConnectionString); nav.MoveToFirstChild(); //nav.MoveToId(entity.Id.ToString()); int maxId = 0; do { int id = int.Parse(nav.GetAttribute("Id", "")); if (id > maxId) { maxId = id; } } while (nav.MoveToNext()); entity.Id = ++maxId; nav.MoveToParent(); XmlWriter writer = nav.AppendChild(); CreateXmlNodeEl(entity, writer); writer.Close(); nav.MoveToNext(); //nav.WriteSubtree(writer); //WriteEntity(entity , nav); //doc.Save(DbProvider.ConnectionString); //nav.WriteSubtree(XmlWriter.Create("C:\\myxml1.xml")); // return(0); }
public string SerializeToStrippedXml(object value) { if (value == null) { throw new ArgumentNullException("value"); } if (value.GetType() != Type) { throw new ArgumentException("The value argument must be of the System.Type that the serializer knows how to serialize"); } XmlDocument xmlDocument = new XmlDocument(); XPathNavigator navigator = xmlDocument.CreateNavigator(); if (navigator == null) { throw new ArgumentNullException("navigator"); } using (XmlWriter xmlWriter = navigator.AppendChild()) { Serializer.Serialize(xmlWriter, value); } return(xmlDocument.FirstChild.InnerXml); }
static void XPathNavigatorMethods_AppendChild4() { // XPathNavigator.AppendChild(XPathNavigator) //<snippet4> XmlDocument document = new XmlDocument(); document.Load("contosoBooks.xml"); XPathNavigator navigator = document.CreateNavigator(); navigator.MoveToChild("bookstore", "http://www.contoso.com/books"); navigator.MoveToChild("book", "http://www.contoso.com/books"); XmlDocument childNodes = new XmlDocument(); childNodes.Load(new StringReader("<pages xmlns=\"http://www.contoso.com/books\">100</pages>")); XPathNavigator childNodesNavigator = childNodes.CreateNavigator(); if (childNodesNavigator.MoveToChild("pages", "http://www.contoso.com/books")) { navigator.AppendChild(childNodesNavigator); } Console.WriteLine(navigator.OuterXml); //</snippet4> }
/// <summary> /// CONVERTIR LISTA EN OBJETO XML /// </summary> /// <param name="Entidad"></param> /// <param name="Root"></param> /// <returns></returns> public static XmlDocument GetEntityXml(ErroresException Entidad, String Root) { XmlDocument xmlDoc = new XmlDocument(); try { XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add("", ""); XmlAttributeOverrides overrides = new XmlAttributeOverrides(); XmlAttributes attr = new XmlAttributes(); attr.XmlRoot = new XmlRootAttribute(Root); overrides.Add(typeof(ErroresException), attr); XPathNavigator nav = xmlDoc.CreateNavigator(); using (XmlWriter writer = nav.AppendChild()) { XmlSerializer ser = new XmlSerializer(typeof(ErroresException), overrides); ser.Serialize(writer, Entidad, ns); } return(xmlDoc); } catch { return(xmlDoc); } }
protected void Button1_Click(object sender, EventArgs e) { if (UserName.Text != null) { if (Password.Text == ConfirmPassword.Text && Password.Text != null) { if (Session["cText"].ToString() == TextBox1.Text) { //add user to XML database //after encryption. EncryptionDecryption encrypter = new EncryptionDecryption(); string encrypted_password = encrypter.Encryption(Password.Text); XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.NewLineOnAttributes = true; XmlDocument xref = new XmlDocument(); xref.Load(HttpContext.Current.Server.MapPath("App_Data/Member.xml")); XPathNavigator nav = xref.CreateNavigator(); nav.MoveToChild("Members", ""); XmlWriter writer = nav.AppendChild(); writer.WriteStartElement("User"); writer.WriteElementString("Username", UserName.Text); writer.WriteElementString("Password", encrypted_password); writer.WriteEndElement(); writer.Close(); xref.Save(HttpContext.Current.Server.MapPath("App_Data/Member.xml")); Response.Redirect("~/Member.aspx"); } else { errorLabel.Visible = true; errorLabel.Text = "Validation incorrect."; } } else { //show pw do not match errorLabel.Visible = true; errorLabel.Text = "Passwords Must Match!"; } } else { errorLabel.Visible = true; errorLabel.Text = "Username cannot be blank"; } }
public void AppendChildStringInvalidFragment() { XPathNavigator nav = GetInstance("<root xmlns='urn:foo'/>"); nav.MoveToFirstChild(); nav.AppendChild("<?xml version='1.0'?><root/>"); }
// the work of the component public override void Apply(XmlDocument document, string key) { // set the key in the XPath context context["key"] = key; // iterate over the copy commands foreach (CopyFromFileCommand copy_command in copy_commands) { // extract the target node XPathExpression target_xpath = copy_command.Target.Clone(); target_xpath.SetContext(context); XPathNavigator target = document.CreateNavigator().SelectSingleNode(target_xpath); // warn if target not found? if (target == null) { continue; } // extract the source nodes XPathExpression source_xpath = copy_command.Source.Clone(); source_xpath.SetContext(context); XPathNodeIterator sources = copy_command.SourceDocument.CreateNavigator().Select(source_xpath); // warn if source not found? // append the source nodes to the target node foreach (XPathNavigator source in sources) { target.AppendChild(source); } } }
public static void SaveNameValueList(ContentURI uri, IDictionary <string, string> lstUpdates, string docPath, string nodeName) { if (lstUpdates.Count > 0) { string sValue = string.Empty; XmlDocument oUpdatesDoc = new XmlDocument(); oUpdatesDoc.LoadXml(Helpers.GeneralHelpers.ROOT_NODE); XPathNavigator navDoc = oUpdatesDoc.CreateNavigator(); //move to the root node navDoc.MoveToFirstChild(); //use an xmlwriter to write remaining nodes XmlWriter oUpdateElWriter = null; foreach (KeyValuePair <string, string> kvp in lstUpdates) { oUpdateElWriter = navDoc.AppendChild(); oUpdateElWriter.WriteStartElement(nodeName); oUpdateElWriter.WriteAttributeString(AppHelpers.Calculator.cId, kvp.Key); oUpdateElWriter.WriteAttributeString(Helpers.GeneralHelpers.VALUE, kvp.Value); oUpdateElWriter.WriteEndElement(); oUpdateElWriter.Dispose(); string sErrorMsg = string.Empty; Helpers.FileStorageIO fileStorageIO = new Helpers.FileStorageIO(); fileStorageIO.SaveXmlInURI(uri, oUpdatesDoc, docPath, out sErrorMsg); } } }
/// <summary> /// Updates the node replacing inheritdoc node with comments found. /// </summary> /// <param name="inheritDocNodeNavigator">Navigator for inheritdoc node</param> /// <param name="contentNodeNavigator">Navigator for content</param> private void UpdateNode(XPathNavigator inheritDocNodeNavigator, XPathNavigator contentNodeNavigator) { // retrieve the selection filter if specified. string selectValue = inheritDocNodeNavigator.GetAttribute("select", String.Empty); if (!String.IsNullOrEmpty(selectValue)) { this.WriteMessage(MessageLevel.Info, "Filter: " + selectValue); sourceExpression = XPathExpression.Compile(selectValue); } inheritDocNodeNavigator.MoveToParent(); bool isInnerText = false; if (inheritDocNodeNavigator.LocalName != "comments" && inheritDocNodeNavigator.LocalName != "element") { sourceExpression = XPathExpression.Compile(inheritDocNodeNavigator.LocalName); isInnerText = true; } else { inheritDocNodeNavigator.MoveTo( this.sourceDocument.CreateNavigator().SelectSingleNode(inheritDocExpression)); } XPathNodeIterator sources = (XPathNodeIterator)contentNodeNavigator.CreateNavigator().Evaluate(sourceExpression); if (isInnerText && sources.Count == 1) { //inheritDocNodeNavigator.DeleteSelf(); inheritDocNodeNavigator.MoveTo( this.sourceDocument.CreateNavigator().SelectSingleNode(inheritDocExpression)); // append the source nodes to the target node foreach (XPathNavigator source in sources) { inheritDocNodeNavigator.ReplaceSelf(source.InnerXml); } } else { inheritDocNodeNavigator.DeleteSelf(); // append the source nodes to the target node foreach (XPathNavigator source in sources) { XPathNodeIterator childIterator = inheritDocNodeNavigator.SelectChildren( source.Name, String.Empty); if (childIterator.Count == 0) { inheritDocNodeNavigator.AppendChild(source); } } } }
private void CreateNodeContainer(XPathNavigator nav) { XmlWriter writer = nav.AppendChild(); writer.WriteStartElement(GetParentNodeName()); writer.WriteEndElement(); writer.Close(); }
public void AppendChildToTextNode() { XPathNavigator nav = GetInstance("<root>text</root>"); nav.MoveToFirstChild(); nav.MoveToFirstChild(); XmlWriter w = nav.AppendChild(); }
public void AppendChildStartDocumentInvalid() { XPathNavigator nav = GetInstance(String.Empty); XmlWriter w = nav.AppendChild(); w.WriteStartDocument(); w.Close(); }
public void AppendChildElementIncomplete() { XPathNavigator nav = GetInstance(String.Empty); XmlWriter w = nav.AppendChild(); w.WriteStartElement("foo"); w.Close(); }
public IXPathNavigable AddRunSettings(IXPathNavigable runSettingDocument, IRunSettingsConfigurationInfo configurationInfo, ILogger logger) { XPathNavigator runSettingsNavigator = runSettingDocument.CreateNavigator(); Debug.Assert(runSettingsNavigator != null, "userRunSettingsNavigator == null!"); if (!runSettingsNavigator.MoveToChild(Constants.RunSettingsName, "")) { logger.Log(MessageLevel.Warning, "RunSettingsDocument does not contain a RunSettings node! Canceling settings merging..."); return(runSettingsNavigator); } var settingsContainer = new RunSettingsContainer(); settingsContainer.SolutionSettings = new RunSettings(); if (CopyToUnsetValues(runSettingsNavigator, settingsContainer)) { runSettingsNavigator.DeleteSelf(); // this node is to be replaced by the final run settings } string solutionRunSettingsFile = GetSolutionSettingsXmlFile(); try { if (File.Exists(solutionRunSettingsFile)) { var solutionRunSettingsDocument = new XPathDocument(solutionRunSettingsFile); XPathNavigator solutionRunSettingsNavigator = solutionRunSettingsDocument.CreateNavigator(); if (solutionRunSettingsNavigator.MoveToChild(Constants.RunSettingsName, "")) { CopyToUnsetValues(solutionRunSettingsNavigator, settingsContainer); } else { logger.Log(MessageLevel.Warning, $"Solution test settings file found at '{solutionRunSettingsFile}', but does not contain {Constants.RunSettingsName} node"); } } } catch (Exception e) { logger.Log(MessageLevel.Warning, $"Solution test settings file could not be parsed, check file: {solutionRunSettingsFile}{Environment.NewLine}Exception: {e}"); } foreach (var projectSettings in settingsContainer.ProjectSettings) { projectSettings.GetUnsetValuesFrom(settingsContainer.SolutionSettings); } GetValuesFromGlobalSettings(settingsContainer); runSettingsNavigator.MoveToChild(Constants.RunSettingsName, ""); runSettingsNavigator.AppendChild(settingsContainer.ToXml().CreateNavigator()); runSettingsNavigator.MoveToRoot(); return(runSettingsNavigator); }
static void Main() { // Создание XPath документа. XPathDocument document = new XPathDocument("Books.xml"); // Единственное назначение XPathDocument - создание навигатора. XPathNavigator navigator = document.CreateNavigator(); // При создании навигатора при помощи XPathDocument // возможно выполнять только чтение. Console.WriteLine(@"Навигатор создан только для чтения. Свойство CanEdit = {0}.", navigator.CanEdit); // Используя XmlDocument навигатор можно использовать и для редактирования. XmlDocument xmldoc = new XmlDocument(); xmldoc.Load("Books.xml"); navigator = xmldoc.CreateNavigator(); Console.WriteLine(@"Навигатор получил возможность редактирования. Свойство CanEdit = {0}.", navigator.CanEdit); // Теперь можно попробовать что-то записать в XML-документ. // Выполняем навигацию к узлу Book. navigator.MoveToChild("ListOfBooks", ""); navigator.MoveToChild("Book", ""); // Проводим вставку значений. navigator.InsertBefore("<InsertBefore>insert_before</InsertBefore>"); navigator.InsertAfter("<InsertAfter>insert_after</InsertAfter>"); navigator.AppendChild("<AppendChild>append_child</AppendChild>"); navigator.MoveToNext("Book", ""); navigator.InsertBefore("<InsertBefore>1111111111</InsertBefore>"); navigator.InsertAfter("<InsertAfter>2222222222</InsertAfter>"); navigator.AppendChild("<AppendChild>3333333333</AppendChild>"); // Сохраняем изменения. xmldoc.Save("Books.xml"); // Задержка. Console.ReadKey(); }
private void EnsureChildNode(XPathNavigator parent, string nodeName) { XPathNavigator child = parent.SelectSingleNode(String.Format("c:{0}", nodeName), _resolver); if (child == null) { parent.AppendChild(String.Format("<{0}/>", nodeName)); } }
static void SaveYarnNodes(List <string> nodes, string name) { XPathNavigator nodesNav = currentGameNav.SelectSingleNode("/Game/Yarn/VisitedNodes/" + name); foreach (string node in nodes) { nodesNav.AppendChild("<Node Name =\"" + node + "\"/>"); } }