/// <summary> /// Called to finish construction when an instruction has been instantiated by /// a factory and had its properties set. /// This can check the integrity of the instruction or perform other initialization tasks. /// </summary> /// <param name="xn">XML node describing the instruction</param> /// <param name="con">Parent xml node instruction</param> /// <returns></returns> public override bool finishCreation(XmlNode xn, Context con) { // finish factory construction Logger.getOnly().isNotNull(m_pathName, @"include must have a 'from' path."); Logger.getOnly().isTrue(m_pathName != "", @"include must have a 'from' path."); string pathname = TestState.getOnly().getScriptPath() + @"\" + m_pathName; XmlDocument doc = new XmlDocument(); doc.PreserveWhitespace = true; // allows <insert> </insert> try { doc.Load(pathname); } catch (System.IO.FileNotFoundException ioe) { Logger.getOnly().fail(@"include '" + pathname + "' not found: " + ioe.Message); } catch (System.Xml.XmlException xme) { Logger.getOnly().fail(@"include '" + pathname + "' not loadable: " + xme.Message); } XmlNode include = doc["include"]; Logger.getOnly().isNotNull(include, "Missing document element 'include'."); XmlElement conEl = con.Element; // clone insert and add it before so there's an insert before and after // after adding elements, delete the "after" one XmlDocumentFragment df = xn.OwnerDocument.CreateDocumentFragment(); df.InnerXml = xn.OuterXml; conEl.InsertBefore(df, xn); foreach (XmlNode xnode in include.ChildNodes) { string image = xnode.OuterXml; if (image.StartsWith("<")) { XmlDocumentFragment dfrag = xn.OwnerDocument.CreateDocumentFragment(); dfrag.InnerXml = xnode.OuterXml; conEl.InsertBefore(dfrag, xn); } } conEl.RemoveChild(xn); //Logger.getOnly().paragraph(Utilities.attrText(textImage)); return(true); }
private void UpdateNodes(XmlNodeList nodes, XmlDocument document) { Log(Level.Verbose, "Updating nodes with value '{0}'.", Value); int index = 0; foreach (XmlNode node in nodes) { Log(Level.Verbose, "Updating node '{0}'.", index); if (this.PokeMode == Mode.Replace) { node.InnerXml = Value; } else if (this.PokeMode == Mode.Add) { node.InnerXml = node.InnerXml + Value; } else if (this.PokeMode == Mode.After) { XmlDocumentFragment Fragment = document.CreateDocumentFragment(); Fragment.InnerXml = Value; node.ParentNode.InsertAfter(Fragment, node); } else if (this.PokeMode == Mode.Before) { XmlDocumentFragment Fragment = document.CreateDocumentFragment(); Fragment.InnerXml = Value; node.ParentNode.InsertBefore(Fragment, node); } else if (this.PokeMode == Mode.ReplaceOuter) { XmlDocumentFragment Fragment = document.CreateDocumentFragment(); Fragment.InnerXml = Value; node.ParentNode.ReplaceChild(Fragment, node); } index++; } Log(Level.Verbose, "Updated all nodes successfully.", Value); }
public static void Main() { //Create the XmlDocument. XmlDocument doc = new XmlDocument(); doc.LoadXml("<items/>"); //Create a document fragment. XmlDocumentFragment docFrag = doc.CreateDocumentFragment(); //Set the contents of the document fragment. docFrag.InnerXml = "<item>widget</item>"; //Add the children of the document fragment to the //original document. doc.DocumentElement.AppendChild(docFrag); Console.WriteLine("Display the modified XML..."); Console.WriteLine(doc.OuterXml); }
public void XacNhanDiLam(string TaiKhoan, int Ngay, int Thang, int Nam) { XmlTextReader textread = new XmlTextReader("ChamCong.xml"); XmlDocument doc = new XmlDocument(); doc.Load(textread); textread.Close(); XmlNode currNode; XmlDocumentFragment docFrag = doc.CreateDocumentFragment(); docFrag.InnerXml = "<ChamCong>" + "<TaiKhoan>" + TaiKhoan + "</TaiKhoan>" + "<Ngay>" + Ngay + "</Ngay>" + "<Thang>" + Thang + "</Thang>" + "<Nam>" + Nam + "</Nam>" + "</ChamCong>"; currNode = doc.DocumentElement; currNode.InsertAfter(docFrag, currNode.LastChild); doc.Save("ChamCong.xml"); }
public XmlDocument GenerateXMLDocument() { XmlDeclaration xmlDeclaration = documentContext.CreateXmlDeclaration("1.0", "UTF-8", null); XmlElement root = documentContext.DocumentElement; documentContext.InsertBefore(xmlDeclaration, root); XmlDocumentFragment xfrag = documentContext.CreateDocumentFragment(); xfrag.InnerXml = @"<?include .\patches\*.xml?>"; documentContext.AppendChild(xfrag); XmlElement rootNode = documentContext.CreateElement(string.Empty, "patches", string.Empty); documentContext.AppendChild(rootNode); foreach (var file in this.ModifiedFiles) { var patchNode = GenerateForFile(file); rootNode.AppendChild(patchNode); } return(documentContext); }
public static void saveUser(User user) { try { XmlDocument document = new XmlDocument(); document.Load("accounts.xml"); XmlDocumentFragment xfrag = document.CreateDocumentFragment(); xfrag.InnerXml = @"<account><username>" + user.UserName + "</username><password>" + user.Password + "</password><api-key>" + user.apiKey + "</api-key><app-name>" + user.appName + "</app-name><proxy>" + user.Proxy + "</proxy></account>"; document.DocumentElement.AppendChild(xfrag); document.Save(new StreamWriter("accounts.xml")); } catch (Exception e) { Console.WriteLine("Could not save user: " + user.UserName + Environment.NewLine + e.Message); } }
public static void Main() { XmlDocument doc = new XmlDocument(); string xmlnodestr = @"<mynode value1='1' value2='123'>abc</mynode> <mynode value1='1' value2='123'>abc</mynode> <mynode value1='1' value2='123'>abc</mynode>"; XmlDocumentFragment frag = doc.CreateDocumentFragment(); frag.InnerXml = xmlnodestr; XmlNodeList nodes = frag.SelectNodes("*"); foreach (XmlNode node in nodes) { Console.WriteLine(node.Name + " value1 = {0}; value2 = {1}", node.Attributes["value1"].Value, node.Attributes["value2"].Value); } }
/// <summary> /// Update the PN data to the final output file /// </summary> /// <param name="data">The input PN data of current item</param> /// <param name="places">Places node parent</param> /// <param name="transitions">Transitions node parent</param> /// <param name="arcs">Arcs node parent</param> private void addPNData(WSNPNData data, ref XmlElement places, ref XmlElement transitions, ref XmlElement arcs) { XmlElement[,] map = new XmlElement[, ] { { data.places, places }, { data.transitions, transitions }, { data.arcs, arcs }, }; XmlDocumentFragment xFrag = null; for (int i = 0; i < map.GetLength(0); i++) { foreach (XmlElement xml in map[i, 0].ChildNodes) { xFrag = mDocOut.CreateDocumentFragment(); xFrag.InnerXml = xml.OuterXml; map[i, 1].AppendChild(xFrag); } } }
public void Set <T>(string namespce, string key, T value) { lock (xml_document) { XmlSerializer serializer = new XmlSerializer(typeof(T)); StringWriter writer = new StringWriter(); serializer.Serialize(writer, value); XmlDocumentFragment fragment = xml_document.CreateDocumentFragment(); fragment.InnerXml = writer.ToString(); writer.Close(); if (fragment.FirstChild is XmlDeclaration) { fragment.RemoveChild(fragment.FirstChild); // This is only a problem with Microsoft's System.Xml } XmlNode namespace_node = GetNamespaceNode(namespce == null ? new string [] { null_namespace } : namespce.Split('.'), true); bool found = false; foreach (XmlNode node in namespace_node.ChildNodes) { if (node.Attributes[tag_identifier_attribute_name].Value == key && node.Name == value_tag_name) { node.InnerXml = fragment.InnerXml; found = true; break; } } if (!found) { XmlNode new_node = xml_document.CreateElement(value_tag_name); XmlAttribute attribute = xml_document.CreateAttribute(tag_identifier_attribute_name); attribute.Value = key; new_node.Attributes.Append(attribute); new_node.AppendChild(fragment); namespace_node.AppendChild(new_node); } QueueWrite(); } }
/// <summary> /// 指定の DefaultLocators.xml ファイルからコメントアウトされた /// 'locator_ref' と 'portal_locators' の要素を カスタムListViewItem のコレクションに抽出 /// </summary> /// <param name="doc"></param> /// <returns></returns> private System.Collections.Generic.List <LocatorItem> getCommentedLocatorsList(XmlDocument doc) { List <LocatorItem> locators = new List <LocatorItem>(); try { XmlNodeList locatorNodes = doc.SelectNodes("//comment()[contains(.,'<locator_ref>')]"); foreach (XmlNode locatorNode in locatorNodes) { XmlDocumentFragment docFrag = doc.CreateDocumentFragment(); docFrag.InnerXml = locatorNode.InnerText; string name = docFrag.SelectSingleNode("//locator_ref/name").InnerText; string dispname = docFrag.SelectSingleNode("//locator_ref/display_name").InnerText; docFrag = null; LocatorItem locator = createLocatorItem(name, dispname, false, LocatorItem.LocatorTypes.SERVER, false); locators.Add(locator); } XmlNodeList portalNodes = doc.SelectNodes("//comment()[contains(.,'<portal_locators>')]"); foreach (XmlNode portalNode in portalNodes) { XmlDocumentFragment docFrag = doc.CreateDocumentFragment(); docFrag.InnerXml = portalNode.InnerText; string name = docFrag.SelectSingleNode("//portal_locators/display_name/@locator_name").Value; string dispname = docFrag.SelectSingleNode("//portal_locators/display_name/@display_name").Value; docFrag = null; LocatorItem locator = createLocatorItem(name, dispname, false, LocatorItem.LocatorTypes.PORTAL, false); locators.Add(locator); } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); } return(locators); }
public override void Serialize(object objectToSerialize, object writer) { if (objectToSerialize == null) { throw new ArgumentNullException("objectToSerialize"); } if (writer == null) { throw new ArgumentNullException("writer"); } if (!(writer is Stream) && !(writer is TextWriter) && !(writer is XmlWriter) && !(writer is string)) { throw new ArgumentException(SR.ExceptionChartSerializerWriterObjectInvalid, "writer"); } XmlDocument xmlDocument = new XmlDocument(); base.binaryFormatVersion = 300; XmlDocumentFragment xmlDocumentFragment = xmlDocument.CreateDocumentFragment(); this.SerializeObject(objectToSerialize, null, base.GetObjectName(objectToSerialize), xmlDocumentFragment, xmlDocument); xmlDocument.AppendChild(xmlDocumentFragment); this.RemoveEmptyChildNodes(xmlDocument); if (writer is Stream) { xmlDocument.Save((Stream)writer); ((Stream)writer).Flush(); ((Stream)writer).Seek(0L, SeekOrigin.Begin); } if (writer is string) { xmlDocument.Save((string)writer); } if (writer is XmlWriter) { xmlDocument.Save((XmlWriter)writer); } if (writer is TextWriter) { xmlDocument.Save((TextWriter)writer); } }
protected void registerBtn_Click(object sender, EventArgs e) { if (Username.Text == "HaoYan" || Username.Text == "ShihuanShao" || Username.Text == "JieGuo" || Username.Text == "YunlongJiang") { Label4.Text = "Your username is not allowed!"; } else if (Password.Text == Confirm.Text) { string fLocation = Path.Combine(Request.PhysicalApplicationPath, @"App_Data\user.xml"); XmlDocument xdoc = new XmlDocument(); xdoc.Load(fLocation); XmlDocumentFragment xfrag = xdoc.CreateDocumentFragment(); xfrag.InnerXml = @"<User><username>" + Username.Text + "</username>" + "<password>" + Password.Text + "</password>" + "</User>"; xdoc.DocumentElement.AppendChild(xfrag); xdoc.Save(fLocation); } else { Label4.Text = "Your confirm password is wrong!"; } }
public static XmlNode NameValCol(XmlNode parent, NameValueCollection col, string val, string nsName) { if (nsName == null) { nsName = parent.NamespaceURI; } if (val != null) { return(NameValColWorkhorse(parent, val, col.GetValues(val), nsName)); } XmlDocumentFragment frag = parent.OwnerDocument.CreateDocumentFragment(); for (int x = 0; x < col.Count; x++) { AppendNode(frag, NameValColWorkhorse(parent, col.GetKey(x), col.GetValues(x), nsName)); } return(frag); }
public static XmlNode CookieCol(XmlNode parent, HttpCookieCollection col, string val, string nsName) { if (nsName == null) { nsName = parent.NamespaceURI; } if (val != null) { return(CookieColWorkhorse(parent, col[val], nsName)); } XmlDocumentFragment frag = parent.OwnerDocument.CreateDocumentFragment(); for (int x = 0; x < col.Count; x++) { AppendNode(frag, CookieColWorkhorse(parent, col[x], nsName)); } return(frag); }
/// <summary> /// 添加调色板配置信息到配置文件 /// </summary> private void AddColorPalettes(XmlDocument m_Doc, XmlElement root) { try { XmlElement colorPalettes = m_Doc.CreateElement("ColorPalettes"); if (g_ColorPalettes != null) { XmlDocumentFragment docFragment = m_Doc.CreateDocumentFragment(); docFragment.InnerXml = g_ColorPalettes.InnerXml; colorPalettes.AppendChild(docFragment); } root.AppendChild(colorPalettes); } catch (System.Exception ex) { Program.ShowError(ex); } }
private void ParseJsonMulti(string input) { List <CmlHelper> molecules = new List <CmlHelper>(); JToken molJson = JObject.Parse(input); JToken mols = molJson.SelectToken("m"); int atomNumber = 0; int bondNumber = 0; foreach (JToken mol in mols) { CmlHelper molHelper = new CmlHelper(mol.ToString(), atomNumber, bondNumber); atomNumber = molHelper.AtomCounter; bondNumber = molHelper.BondCounter; molecules.Add(molHelper); } _xmlDocument = CreateCmlDocument(molecules[0].GetMolecule().OuterXml, true); _xmlNamespaceManager = new XmlNamespaceManager(_xmlDocument.NameTable); _xmlNamespaceManager.AddNamespace(NamespacePrefix, NamespaceUri); int moleculeCounter = 0; SetMoleculeId("m" + moleculeCounter); moleculeCounter++; XmlNode cmlNode = _xmlDocument.SelectSingleNode("//cml:cml", _xmlNamespaceManager); for (int i = 1; i < molecules.Count; i++) { molecules[i].SetMoleculeId("m" + moleculeCounter); moleculeCounter++; XmlNode mol = molecules[i].GetMolecule(); XmlDocumentFragment fragment = _xmlDocument.CreateDocumentFragment(); fragment.InnerXml = mol.OuterXml; cmlNode.AppendChild(fragment); } }
private XmlNode GetXmlData() { XmlDocumentFragment fDoc = _Draw.ReportDocument.CreateDocumentFragment(); XmlNode rows = _Draw.CreateElement(fDoc, "fyi:Rows", null); foreach (DataRow dr in _DataTable.Rows) { XmlNode row = _Draw.CreateElement(rows, "Row", null); bool bRowBuilt = false; foreach (DataColumn dc in _DataTable.Columns) { if (dr[dc] == DBNull.Value) { continue; } string val; if (dc.DataType == typeof(DateTime)) { val = Convert.ToString(dr[dc], System.Globalization.DateTimeFormatInfo.InvariantInfo); } else { val = Convert.ToString(dr[dc], NumberFormatInfo.InvariantInfo); } if (val == null) { continue; } _Draw.CreateElement(row, dc.ColumnName, val); bRowBuilt = true; // we've populated at least one column; so keep row } if (!bRowBuilt) { rows.RemoveChild(row); } } return(rows); }
/// <summary> /// Update the PN data to the final output file /// </summary> /// <param name="data">The input PN data of current item</param> /// <param name="places">Places node parent</param> /// <param name="transitions">Transitions node parent</param> /// <param name="arcs">Arcs node parent</param> private void addPNData(WSNPNData data, ref XmlElement places, ref XmlElement transitions, ref XmlElement arcs) { XmlElement[,] map = new XmlElement[, ] { { data.places, places }, { data.transitions, transitions }, { data.arcs, arcs }, }; XmlDocumentFragment xFrag = null; for (int i = 0; i < map.GetLength(0); i++) { foreach (XmlElement xml in map[i, 0].ChildNodes) { xFrag = _docOut.CreateDocumentFragment(); xFrag.InnerXml = xml.OuterXml; map[i, 1].AppendChild(xFrag); } } //Log.d(TAG, string.Format("In: {0} --- Out: {1}", data.inPos, data.outPos)); }
private void MergeProcessInXHTMLforMasterPage(string xhtmlFileName) { string projectFolder = Path.GetDirectoryName(xhtmlFileName); string[] fileNames = Directory.GetFiles(projectFolder, "*.xhtml"); if (ValidateXHTMLFiles(fileNames)) { string mainFileName = Common.PathCombine(projectFolder, "Main.xhtml"); string flexRevFileName = Common.PathCombine(projectFolder, "FlexRev.xhtml"); if (File.Exists(flexRevFileName)) { XmlDocument xDocRev = Common.DeclareXMLDocument(false); XmlNamespaceManager namespaceManagerRev = new XmlNamespaceManager(xDocRev.NameTable); namespaceManagerRev.AddNamespace("xhtml", "http://www.w3.org/1999/xhtml"); xDocRev.Load(flexRevFileName); XmlNodeList divNodesRev = xDocRev.SelectNodes("//xhtml:body/xhtml:div", namespaceManagerRev); if (divNodesRev != null) { XmlDocument xDocMain = Common.DeclareXMLDocument(false); XmlNamespaceManager namespaceManagerMain = new XmlNamespaceManager(xDocMain.NameTable); namespaceManagerMain.AddNamespace("xhtml", "http://www.w3.org/1999/xhtml"); xDocMain.Load(mainFileName); XmlNode bodyNodeMain = xDocMain.SelectSingleNode("//xhtml:body", namespaceManagerMain); if (bodyNodeMain != null) { XmlDocumentFragment styleNode = xDocMain.CreateDocumentFragment(); styleNode.InnerXml = "<div class=\"mergeBreak\"></div>"; bodyNodeMain.AppendChild(styleNode); for (int i = 0; i < divNodesRev.Count; i++) { XmlNode importNode = xDocMain.ImportNode(divNodesRev[i].CloneNode(true), true); bodyNodeMain.AppendChild(importNode); } } xDocMain.Save(mainFileName); } } } }
//Обработка правил public void RuleWork() { //TReasoner.UpdateEventsTime(CurrentData, StepNum); Rules.Clear(); foreach (XElement grule in GeneralRules) { Rules.AddRange(TReasoner.EvalGeneral(grule, ClassesDic)); } foreach (XElement prule in PrivateRules) { Rules.Add(new XElement(prule)); } TReasoner.EvalRules(Rules, CurrentData, PreviousData, StepNum); XmlDocument xdoc = new XmlDocument(); xdoc.Load("TKBnew.xml"); XmlNode childNode = xdoc.SelectSingleNode("/knowledge-base/classes/class[@id='world']/rules"); // apply your xpath here childNode.ParentNode.RemoveChild(childNode); XmlDocumentFragment xfrag = xdoc.CreateDocumentFragment(); xfrag.InnerXml = "<rules></rules>"; XmlNode childNode2 = xdoc.SelectSingleNode("knowledge-base/classes/class[@id='world']"); childNode2.AppendChild(xfrag); XmlNode RuleschildNode = xdoc.SelectSingleNode("knowledge-base/classes/class[@id='world']/rules"); foreach (XElement rule in Rules) { xfrag.InnerXml = rule.ToString(); RuleschildNode.AppendChild(xfrag); } xdoc.Save("TKBnewforAT.xml"); }
public override void Process(IXmlProcessorNodeList nodeList, IXmlProcessorEngine engine) { XmlProcessingInstruction node = nodeList.Current as XmlProcessingInstruction; XmlDocumentFragment fragment = CreateFragment(node); string expression = node.Data; // We don't have an expression evaluator right now, so expression will // be just pre-defined literals that we know how to evaluate object evaluated = ""; if (string.Compare(expression, "$basedirectory", true) == 0) { evaluated = AppDomain.CurrentDomain.BaseDirectory; } fragment.AppendChild(node.OwnerDocument.CreateTextNode(evaluated.ToString())); ReplaceNode(node.ParentNode, fragment, node); }
/// <summary> /// This method creates Project XML /// connects to mongodb, fetches all Department documents to a list /// For each item in list we convert that to XML string using JsonConvert.DeserializeXmlNode /// these individual xml nodes are added to blank xml document with documents as root node /// </summary> private static async void createDepartmentXML() { _client = new MongoClient(); //Creating client _database = _client.GetDatabase("project2"); //Connecting to database var collection = _database.GetCollection <BsonDocument>("department"); //Selecting collection var filter = new BsonDocument(); var results = await collection.Find(filter).Project("{_id: 0}").ToListAsync(); //Fetching from MongoDb as a list of json strings XmlDocument doc = new XmlDocument(); XmlNode rootNode = doc.CreateElement("departments"); //Blank XML Document with root node departments doc.AppendChild(rootNode); foreach (var result in results) //Iterating over each JSON object { //Creating XML node with XML got by converting JSON, and adding node to XML Document XmlDocumentFragment proj = doc.CreateDocumentFragment(); proj.InnerXml = JsonConvert.DeserializeXmlNode(result.ToJson(), "department").InnerXml; rootNode.AppendChild(proj); } Console.WriteLine(doc.OuterXml); doc.Save("department.xml"); }
private void button5_Click(object sender, EventArgs e) { if (comboBox1.SelectedIndex <= -1 && comboBox2.SelectedIndex <= -1) { MessageBox.Show("No has seleccionado algun valor"); } else { string hijo = ""; string padre = ""; hijo = comboBox1.SelectedItem.ToString(); padre = comboBox2.SelectedItem.ToString(); MessageBox.Show(hijo + " hereda de " + padre); string busca = "<Id>" + hijo + "</Id>"; string agregaSiE = "<HeredaDe>" + padre + "</HeredaDe>"; string agrega = "<" + hijo + "><HeredaDe>" + padre + "</HeredaDe></" + hijo + ">"; string xml = richTextBox2.Text; XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(xml); XmlDocumentFragment xmlDocFragment = xmlDoc.CreateDocumentFragment(); xmlDocFragment.InnerXml = agrega; xmlDoc.SelectSingleNode("umldiagrams").AppendChild(xmlDocFragment); StringWriter sw = new StringWriter(); XmlTextWriter tx = new XmlTextWriter(sw); xmlDoc.WriteTo(tx); Console.WriteLine(sw.ToString()); richTextBox2.Text = ""; richTextBox2.Text = sw.ToString(); string json = JsonConvert.SerializeXmlNode(xmlDoc); richTextBox3.Text = json; Console.WriteLine(json); } }
public static void LogEkle(DataTable table) { XmlDocument document = new XmlDocument(); document.Load(HttpContext.Current.Server.MapPath("~/tiger.xml")); XmlNode root = document.SelectSingleNode("/root"); root.RemoveAll(); XmlDocumentFragment xdf = document.CreateDocumentFragment(); foreach (System.Data.DataRow row in table.Rows) { foreach (System.Data.DataColumn column in table.Columns) { var colunmname = column.ColumnName.Replace(" ", ""); var columnTR = String.Join("", column.ColumnName.Normalize(System.Text.NormalizationForm.FormD).Where(x => char.GetUnicodeCategory(x) != System.Globalization.UnicodeCategory.NonSpacingMark)); xdf.InnerXml = "<item><" + colunmname + ">" + row[column].ToString() + "</" + colunmname + "></item>"; root.InsertAfter(xdf, root.LastChild); } } document.Save(HttpContext.Current.Server.MapPath("~/tiger.xml")); }
public override void Serialize(object objectToSerialize, object writer) { if (objectToSerialize == null) { throw new ArgumentNullException("objectToSerialize"); } if (writer == null) { throw new ArgumentNullException("writer"); } if (!(writer is Stream) && !(writer is TextWriter) && !(writer is XmlWriter) && !(writer is string)) { throw new ArgumentException(Utils.SRGetStr("ExceptionSerializerInvalidWriter"), "writer"); } XmlDocument xmlDocument = new XmlDocument(); XmlDocumentFragment xmlDocumentFragment = xmlDocument.CreateDocumentFragment(); SerializeObject(objectToSerialize, null, GetObjectName(objectToSerialize), xmlDocumentFragment, xmlDocument); xmlDocument.AppendChild(xmlDocumentFragment); RemoveEmptyChildNodes(xmlDocument); if (writer is Stream) { xmlDocument.Save((Stream)writer); ((Stream)writer).Flush(); ((Stream)writer).Seek(0L, SeekOrigin.Begin); } if (writer is string) { xmlDocument.Save((string)writer); } if (writer is XmlWriter) { xmlDocument.Save((XmlWriter)writer); } if (writer is TextWriter) { xmlDocument.Save((TextWriter)writer); } }
public static void AddSectionDashboard() { var saveFile = false; const string dashboardPath = "~/config/dashboard.config"; //Path to the file resolved string dashboardFilePath = HostingEnvironment.MapPath(dashboardPath); //Load settings.config XML file var dashboardXml = new XmlDocument(); dashboardXml.Load(dashboardFilePath ?? ""); XmlNode firstTab = dashboardXml.SelectSingleNode("//section [@alias='StartupDashboardSection']/areas"); if (firstTab != null) { const string xmlToAdd = "<tab caption='Promote'>" + "<control addPanel='true' panelCaption=''>/app_plugins/promote/backoffice/views/dashboard.html</control>" + "</tab>"; //Load in the XML string above XmlDocumentFragment frag = dashboardXml.CreateDocumentFragment(); frag.InnerXml = xmlToAdd; //Append the xml above to the dashboard node dashboardXml.SelectSingleNode("//section [@alias='StartupDashboardSection']")?.InsertAfter(frag, firstTab); //Save the file flag to true saveFile = true; } //If saveFile flag is true then save the file if (saveFile && !string.IsNullOrEmpty(dashboardFilePath)) { //Save the XML file dashboardXml.Save(dashboardFilePath); } }
public override void Serialize(object objectToSerialize, object writer) { if (objectToSerialize == null) { throw new ArgumentNullException("objectToSerialize"); } if (writer == null) { throw new ArgumentNullException("writer"); } if (!(writer is Stream) && !(writer is TextWriter) && !(writer is XmlWriter) && !(writer is string)) { throw new ArgumentException("Invalid type of writer object. Can be Stream, TextWriter, XmlWriter or String (file name)", "writer"); } XmlDocument xmlDocument = new XmlDocument(); XmlDocumentFragment xmlDocumentFragment = xmlDocument.CreateDocumentFragment(); this.SerializeObject(objectToSerialize, null, base.GetObjectName(objectToSerialize), xmlDocumentFragment, xmlDocument); xmlDocument.AppendChild(xmlDocumentFragment); this.RemoveEmptyChildNodes(xmlDocument); if (writer is Stream) { xmlDocument.Save((Stream)writer); ((Stream)writer).Flush(); ((Stream)writer).Seek(0L, SeekOrigin.Begin); } if (writer is string) { xmlDocument.Save((string)writer); } if (writer is XmlWriter) { xmlDocument.Save((XmlWriter)writer); } if (writer is TextWriter) { xmlDocument.Save((TextWriter)writer); } }
/// <summary> /// XmlNodeList의 Node들을 parentNode에 추가한다. /// </summary> /// <param name="parentNode">대상 Element</param> /// <param name="elementList">XmlNodeList 형식의 Element (같은 Level의 Element만 써야한다.)</param> /// <returns>추가된 XmlNode의 갯수</returns> public static int AddElementList(this XmlNode parentNode, XmlNodeList elementList) { var count = 0; if (elementList == null || elementList.Count == 0) { return(count); } CheckNull(parentNode); XmlDocumentFragment fragment = parentNode.OwnerDocument.CreateDocumentFragment(); foreach (XmlNode srcNode in elementList) { fragment.AppendChild(srcNode.CloneNode(true)); count++; } parentNode.AppendChild(fragment); return(count); }
private ResponseHandler(string rawResponse, X509Certificate2 myCert) { this.myCert = myCert; System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding(); this.xmlDocResponse = new XmlDocument(); this.xmlDocResponse.PreserveWhitespace = true; this.xmlDocResponse.XmlResolver = null; this.xmlDocResponse.LoadXml(rawResponse); if (DoesNeedToBeDecrypted()) { //Login.LogToEventLog("ResponseHandler(encrypted)","ResponseHandler(encrypted) : enter"); //get cipher key var decodedCipherKey = GetCipherKey(xmlDocResponse, myCert); //Login.LogToEventLog("ResponseHandler(encrypted)","ResponseHandler(encrypted) : cipherKey : " + decodedCipherKey); //get encrypted data XmlNode node = GetNode("/samlp:Response/saml:EncryptedAssertion/xenc:EncryptedData/xenc:CipherData/xenc:CipherValue"); if (node == null) { throw new Exception("CipherValue node not found"); } string cipherValue = node.InnerText; //LogToEventLog("ResponseHandler(encrypted)","GetNameID(encrypted) : ciphervalue {0}", cipherValue); EncryptionHelper encryptionHelper = new EncryptionHelper(decodedCipherKey); string decryptedValue = encryptionHelper.AesDecrypt(cipherValue); Login.LogToEventLog("ResponseHandler(encrypted)", "Response : " + xmlDocResponse.OuterXml); Login.LogToEventLog("ResponseHandler(encrypted)", "decryptedValue : " + decryptedValue); //add decrypted assertion node to the document XmlDocumentFragment xfrag = xmlDocResponse.CreateDocumentFragment(); xfrag.InnerXml = decryptedValue; xmlDocResponse.DocumentElement.AppendChild(xfrag); } }
public void transform(XmlDocument xmlDoc) { // if no root set then root element as document root if (root == null) { root = (XmlElement)xmlDoc.SelectSingleNode("/*"); } // if required, create elements that don't exist in the target xpath if (createNode) { utils.createXpath(xmlDoc, root, xpath); } // get matching elements XmlNodeList matchingNodes = root.SelectNodes(xpath); foreach (XmlNode matchingNode in matchingNodes) { XmlElement matchingElement = (XmlElement)matchingNode; // create AddXML fragment XmlDocumentFragment xfrag = xmlDoc.CreateDocumentFragment(); xfrag.InnerXml = addXML; // strip fragment (with recursion) foreach (XmlNode childNode in xfrag.ChildNodes) { if (childNode.NodeType == XmlNodeType.Element) { utils.stripNode(childNode, true); } } matchingElement.AppendChild(xfrag); // strip parent element (no recursion) utils.stripNode(matchingElement, false); } }
// Set up for the tests. protected override void Setup() { doc = new XmlDocument(); fragment = doc.CreateDocumentFragment(); }