public void Save(Control murpleControl, string filename, PodGroup thisPodGroup) { StreamWriter streamWriter = new StreamWriter(filename); XmlWriter xmlWriter = XmlWriter.Create(streamWriter); XmlDocument document = new XmlDocument(); document.AppendChild(document.CreateWhitespace("\n")); { XmlElement murpleElement = document.CreateElement("Murple"); AddNewLine(document, murpleElement); foreach (KeyValuePair<System.Guid, Pod> thisPodPair in murpleControl.Pods) { if(thisPodGroup.ContainsPod(thisPodPair.Key) == true) AddPod(document, murpleElement, thisPodPair); } document.AppendChild(murpleElement); } document.Save(xmlWriter); streamWriter.Close(); }
public bool Save(string path) { bool saved = true; XmlDocument m_Xdoc = new XmlDocument(); try { m_Xdoc.RemoveAll(); XmlNode node = m_Xdoc.CreateXmlDeclaration("1.0", "utf-8", string.Empty); m_Xdoc.AppendChild(node); node = m_Xdoc.CreateComment($" Profile Configuration Data. {DateTime.Now} "); m_Xdoc.AppendChild(node); node = m_Xdoc.CreateWhitespace("\r\n"); m_Xdoc.AppendChild(node); node = m_Xdoc.CreateNode(XmlNodeType.Element, "Profile", null); m_Xdoc.AppendChild(node); m_Xdoc.Save(path); } catch { saved = false; } return saved; }
public void GetReady () { document = new XmlDocument (); document.LoadXml ("<root><foo></foo></root>"); XmlElement element = document.CreateElement ("foo"); whitespace = document.CreateWhitespace ("\r\n"); element.AppendChild (whitespace); doc2 = new XmlDocument (); doc2.PreserveWhitespace = true; }
public static void ImportWhiteSpace() { var whitespace = " "; var tempDoc = new XmlDocument(); var nodeToImport = tempDoc.CreateWhitespace(whitespace); var xmlDocument = new XmlDocument(); var node = xmlDocument.ImportNode(nodeToImport, true); Assert.Equal(xmlDocument, node.OwnerDocument); Assert.Equal(XmlNodeType.Whitespace, node.NodeType); Assert.Equal(whitespace, node.Value); }
public void AddPolygonToSvg( XmlElement svgElement, XmlDocument htmlDoc ) { XmlElement regionElement = htmlDoc.CreateElement ("g"); var regionNameAttr = htmlDoc.CreateAttribute("name"); regionNameAttr.Value = Name; regionElement.Attributes.Append (regionNameAttr); var regionClassAttr = htmlDoc.CreateAttribute ("class"); regionClassAttr.Value = "PoliticalRegion"; regionElement.Attributes.Append (regionClassAttr); // Shape for (int iSubRegion = 0; iSubRegion < Geometry.NumGeometries; iSubRegion += 1) { var subRegionNode = htmlDoc.CreateElement ("polygon"); // Define subregion border. var subRegion = Geometry.GetGeometryN (iSubRegion); var coords = subRegion.Coordinates; var coordStrings = coords.Select (coord => string.Format ("{0:F2},{1:F2} ", coord.X, -coord.Y)); string coordString = coordStrings.Aggregate ((coordStringBase, coordStringNext) => coordStringBase + coordStringNext); var pointsAttr = htmlDoc.CreateAttribute ("points"); pointsAttr.Value = coordString; subRegionNode.Attributes.Append(pointsAttr); // Color/Style spec. var styleAttr = htmlDoc.CreateAttribute ("style"); styleAttr.Value = StyleSpec; subRegionNode.Attributes.Append(styleAttr); // Add state polygon, text to list regionElement.AppendChild (htmlDoc.CreateWhitespace ("\n")); regionElement.AppendChild (subRegionNode); } // Add state polygon, text to list svgElement.AppendChild (htmlDoc.CreateWhitespace ("\n")); svgElement.AppendChild (regionElement); }
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 + "'"); } }
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 (!string.IsNullOrEmpty(propertyName) && 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); Dictionary<string, string> 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 && reader.TokenType != JsonToken.StartConstructor) { // 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) { DateTime d = (DateTime)reader.Value; element.AppendChild(document.CreateTextNode(XmlConvert.ToString(d, DateTimeUtils.ToSerializationMode(d.Kind)))); } 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; } }
private static int Detokenize(Tuplet<ArrayDiffKind, Token>[] tokens, int index, XmlElement current, XmlDocument doc) { for(; index < tokens.Length; ++index) { Tuplet<ArrayDiffKind, Token> 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; }
/** * Reply to the http request */ public XmlDocument GetSnapshot(string regionName) { CheckStale(); XmlDocument requestedSnap = new XmlDocument(); requestedSnap.AppendChild(requestedSnap.CreateXmlDeclaration("1.0", null, null)); requestedSnap.AppendChild(requestedSnap.CreateWhitespace("\r\n")); XmlNode regiondata = requestedSnap.CreateNode(XmlNodeType.Element, "regiondata", ""); try { if (string.IsNullOrEmpty(regionName)) { XmlNode timerblock = requestedSnap.CreateNode(XmlNodeType.Element, "expire", ""); timerblock.InnerText = m_period.ToString(); regiondata.AppendChild(timerblock); regiondata.AppendChild(requestedSnap.CreateWhitespace("\r\n")); foreach (Scene scene in m_scenes) { regiondata.AppendChild(m_snapStore.GetScene(scene, requestedSnap)); } } else { Scene scene = SceneForName(regionName); regiondata.AppendChild(m_snapStore.GetScene(scene, requestedSnap)); } requestedSnap.AppendChild(regiondata); regiondata.AppendChild(requestedSnap.CreateWhitespace("\r\n")); } catch (XmlException e) { m_log.Warn("[DATASNAPSHOT]: XmlException while trying to load snapshot: " + e.ToString()); requestedSnap = GetErrorMessage(regionName, e); } catch (Exception e) { m_log.Warn("[DATASNAPSHOT]: Caught unknown exception while trying to load snapshot: " + e.StackTrace); requestedSnap = GetErrorMessage(regionName, e); } return requestedSnap; }
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); }
private void CreateAction() { XmlDocument document = new XmlDocument(); XmlNode node = document.CreateXmlDeclaration("1.0", "utf-8", string.Empty); document.AppendChild(node); node = document.CreateComment($" Special Actions Configuration Data. {DateTime.Now} "); document.AppendChild(node); node = document.CreateWhitespace("\r\n"); document.AppendChild(node); node = document.CreateNode(XmlNodeType.Element, "Actions", string.Empty); document.AppendChild(node); document.Save(m_Actions); }
private bool SetPropertyValue(XmlDocument xmlDoc, string PropertyName, string NewValue) { XmlNode parentNode = xmlDoc.DocumentElement.SelectSingleNode("appSettings"); if (parentNode == null) { parentNode = xmlDoc.CreateElement("appSettings"); xmlDoc.DocumentElement.AppendChild(xmlDoc.CreateWhitespace("\r\n ")); xmlDoc.DocumentElement.AppendChild(parentNode); xmlDoc.DocumentElement.AppendChild(xmlDoc.CreateWhitespace("\r\n")); } return XmlHelper.SetPropertyValue(xmlDoc, PropertyName, NewValue, parentNode, "add", "key", "value"); }
public void AsText_on_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.CreateWhitespace(" ")); var doc = new XDoc(document); Assert.AreEqual(" ", doc["x"][0].AsText); }
private XmlNode LoadNode(bool skipOverWhitespace) { XmlReader r = this.reader; XmlNode parent = null; XmlElement element; 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 { node = element; break; } case XmlNodeType.EndElement: if (parent == null) { return(null); } Debug.Assert(parent.NodeType == XmlNodeType.Element); 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); }
public override void WriteWhitespace(string ws) { WritePossiblyTopLevelNode(doc.CreateWhitespace(ws), true); }
private void AddNewLine(XmlDocument document, XmlElement targetElement) { targetElement.AppendChild(document.CreateWhitespace("\n")); }
private void Page_Load(object sender, System.EventArgs e) { Response.ExpiresAbsolute = new DateTime(1980, 1, 1, 0, 0, 0, 0); Response.CacheControl = "no-cache"; XmlDocument xml = new XmlDocument(); xml.PreserveWhitespace = true; xml.AppendChild(xml.CreateXmlDeclaration("1.0", "UTF-8", null)); xml.AppendChild(xml.CreateWhitespace("\n")); XmlNode xConnector = xml.CreateElement("Connector"); xml.AppendChild(xConnector); try { string sCommand = Sql.ToString(Request["Command" ]); string sResourceType = Sql.ToString(Request["Type" ]); string sCurrentFolder = Sql.ToString(Request["CurrentFolder"]); if ( !Security.IsAuthenticated() ) { xConnector.AppendChild(xml.CreateWhitespace("\n\t")); XmlUtil.SetSingleNodeAttribute(xml, "Error", "number", "1"); XmlUtil.SetSingleNodeAttribute(xml, "Error", "text" , "Authentication is required."); xConnector.AppendChild(xml.CreateWhitespace("\n")); } else if ( Sql.IsEmptyString(sCommand) || Sql.IsEmptyString(sResourceType) || Sql.IsEmptyString(sCurrentFolder) ) { xConnector.AppendChild(xml.CreateWhitespace("\n\t")); XmlUtil.SetSingleNodeAttribute(xml, "Error", "number", "1"); XmlUtil.SetSingleNodeAttribute(xml, "Error", "text" , "Invalid request."); xConnector.AppendChild(xml.CreateWhitespace("\n")); } else { string sSiteURL = Utils.MassEmailerSiteURL(Context.Application); string sFileURL = sSiteURL + "Images/EmailImage.aspx?ID="; switch ( sCommand ) { case "FileUpload": { int nErrorNumber = 0; string sFileName = String.Empty; string sCustomMsg = String.Empty; Guid gImageID = Guid.Empty; DbProviderFactory dbf = DbProviderFactories.GetFactory(); using ( IDbConnection con = dbf.CreateConnection() ) { con.Open(); // 10/07/2009 We need to create our own global transaction ID to support auditing and workflow on SQL Azure, PostgreSQL, Oracle, DB2 and MySQL. using ( IDbTransaction trn = Sql.BeginTransaction(con) ) { try { FileWorkerUtils.LoadImage(ref gImageID, ref sFileName, trn); if ( Sql.IsEmptyGuid(gImageID) ) nErrorNumber = 202; else sFileURL += gImageID.ToString(); trn.Commit(); } catch { trn.Rollback(); throw; } } } Response.Write("<script type=\"text/javascript\">\n"); Response.Write("window.parent.frames['frmUpload'].OnUploadCompleted(" + nErrorNumber.ToString() + ",'" + Sql.EscapeJavaScript(sFileURL) + "','" + Sql.EscapeJavaScript(sFileName) + "','" + Sql.EscapeJavaScript(sCustomMsg) + "');\n"); Response.Write("</script>\n"); return; } case "GetFolders": { XmlUtil.SetSingleNodeAttribute(xml, xConnector, "command" , sCommand ); XmlUtil.SetSingleNodeAttribute(xml, xConnector, "resourceType", sResourceType); xConnector.AppendChild(xml.CreateWhitespace("\n\t")); XmlUtil.SetSingleNodeAttribute(xml, "CurrentFolder", "path" , sCurrentFolder); XmlUtil.SetSingleNodeAttribute(xml, "CurrentFolder", "url" , sFileURL ); xConnector.AppendChild(xml.CreateWhitespace("\n\t")); XmlUtil.SetSingleNode (xml, "Folders" , ""); xConnector.AppendChild(xml.CreateWhitespace("\n")); break; } case "GetFoldersAndFiles": { XmlUtil.SetSingleNodeAttribute(xml, xConnector, "command" , sCommand ); XmlUtil.SetSingleNodeAttribute(xml, xConnector, "resourceType", sResourceType); xConnector.AppendChild(xml.CreateWhitespace("\n\t")); XmlUtil.SetSingleNodeAttribute(xml, "CurrentFolder", "path" , sCurrentFolder); XmlUtil.SetSingleNodeAttribute(xml, "CurrentFolder", "url" , sFileURL ); xConnector.AppendChild(xml.CreateWhitespace("\n\t")); XmlUtil.SetSingleNode (xml, "Folders" , ""); xConnector.AppendChild(xml.CreateWhitespace("\n\t")); XmlUtil.SetSingleNode (xml, "Files" , ""); xConnector.AppendChild(xml.CreateWhitespace("\n")); DbProviderFactory dbf = DbProviderFactories.GetFactory(); using ( IDbConnection con = dbf.CreateConnection() ) { con.Open(); string sSQL ; sSQL = "select * " + ControlChars.CrLf + " from vwEMAIL_IMAGES" + ControlChars.CrLf + " order by FILENAME " + ControlChars.CrLf; using ( IDbCommand cmd = con.CreateCommand() ) { cmd.CommandText = sSQL; using ( IDataReader rdr = cmd.ExecuteReader() ) { XmlNode xFiles = xConnector.SelectSingleNode("Files"); while ( rdr.Read() ) { Guid gID = Sql.ToGuid (rdr["ID" ]); string sFILENAME = Sql.ToString(rdr["FILENAME" ]); long lFILE_SIZE = Sql.ToLong (rdr["FILE_SIZE"]); XmlNode xFile = xml.CreateElement("File" ); XmlUtil.SetSingleNodeAttribute(xml, xFile, "name", sFILENAME); XmlUtil.SetSingleNodeAttribute(xml, xFile, "size", lFILE_SIZE.ToString()); XmlUtil.SetSingleNodeAttribute(xml, xFile, "url", sFileURL + gID.ToString()); xFiles.AppendChild(xml.CreateWhitespace("\n\t\t")); xFiles.AppendChild(xFile); } xFiles.AppendChild(xml.CreateWhitespace("\n\t")); } } } break; } case "CreateFolder": { xConnector.AppendChild(xml.CreateWhitespace("\n\t")); XmlUtil.SetSingleNodeAttribute(xml, "Error", "number", "103"); XmlUtil.SetSingleNodeAttribute(xml, "Error", "text" , "Folders cannot be created."); xConnector.AppendChild(xml.CreateWhitespace("\n")); break; } } } } catch(Exception ex) { SplendidError.SystemError(new StackTrace(true).GetFrame(0), ex); xConnector.RemoveAll(); xConnector.AppendChild(xml.CreateWhitespace("\n\t")); XmlUtil.SetSingleNodeAttribute(xml, "Error", "number", "1"); XmlUtil.SetSingleNodeAttribute(xml, "Error", "text" , ex.Message); xConnector.AppendChild(xml.CreateWhitespace("\n")); } Response.ContentEncoding = System.Text.UTF8Encoding.UTF8; Response.ContentType = "text/xml"; Response.Write(xml.OuterXml); }
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); }
public void SaveDictToXML(String xmlFileName) { XmlDocument doc = new XmlDocument(); XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null); doc.AppendChild(docNode); XmlWhitespace xml_declaration_newLine = doc.CreateWhitespace("\r\n"); doc.InsertAfter(xml_declaration_newLine, docNode); XmlNode tourNode = doc.CreateElement("TourStoryboard"); XmlAttribute tourNode_displayName = doc.CreateAttribute("displayName"); XmlAttribute tourNode_description = doc.CreateAttribute("description"); //// duratoin experiment XmlAttribute tourNode_duration = doc.CreateAttribute("duration"); tourNode_duration.Value = tourStoryboard.totalDuration.ToString(); tourNode.Attributes.Append(tourNode_duration); tourNode_displayName.Value = tourStoryboard.displayName; tourNode_description.Value = tourStoryboard.description; tourNode.Attributes.Append(tourNode_displayName); tourNode.Attributes.Append(tourNode_description); doc.AppendChild(tourNode); foreach (Timeline tl in tourBiDictionary.firstKeys) { TourTL tourTL = (TourTL)tl; BiDictionary<double, TourEvent> tourTL_dict = tourBiDictionary[tl][0]; if ((tourTL.type == TourTLType.artwork) || (tourTL.type == TourTLType.media) || tourTL.type == TourTLType.highlight || tourTL.type == TourTLType.path) { XmlNode TLNode = doc.CreateElement("TourParallelTL"); XmlAttribute TLNode_type = doc.CreateAttribute("type"); XmlAttribute TLNode_displayName = doc.CreateAttribute("displayName"); XmlAttribute TLNode_file = doc.CreateAttribute("file"); TLNode_type.Value = tourTL.type.ToString(); TLNode_displayName.Value = tourTL.displayName; TLNode_file.Value = tourTL.file; TLNode.Attributes.Append(TLNode_type); TLNode.Attributes.Append(TLNode_displayName); TLNode.Attributes.Append(TLNode_file); tourNode.AppendChild(TLNode); foreach (double beginTime in tourTL_dict.firstKeys) { TourEvent tourEvent = tourTL_dict[beginTime][0]; if (tourEvent.type == TourEvent.Type.zoomMSI) { ZoomMSIEvent zoomMSIEvent = (ZoomMSIEvent)tourEvent; XmlNode TourEventNode = doc.CreateElement("TourEvent"); XmlAttribute TourEventNode_beginTime = doc.CreateAttribute("beginTime"); XmlAttribute TourEventNode_type = doc.CreateAttribute("type"); XmlAttribute TourEventNode_scale = doc.CreateAttribute("scale"); XmlAttribute TourEventNode_toMSIPointX = doc.CreateAttribute("toMSIPointX"); XmlAttribute TourEventNode_toMSIPointY = doc.CreateAttribute("toMSIPointY"); XmlAttribute TourEventNode_duration = doc.CreateAttribute("duration"); TourEventNode_beginTime.Value = beginTime.ToString(); TourEventNode_type.Value = "ZoomMSIEvent"; TourEventNode_scale.Value = zoomMSIEvent.absoluteScale.ToString(); TourEventNode_toMSIPointX.Value = zoomMSIEvent.zoomToMSIPointX.ToString(); TourEventNode_toMSIPointY.Value = zoomMSIEvent.zoomToMSIPointY.ToString(); TourEventNode_duration.Value = zoomMSIEvent.duration.ToString(); TourEventNode.Attributes.Append(TourEventNode_beginTime); TourEventNode.Attributes.Append(TourEventNode_type); TourEventNode.Attributes.Append(TourEventNode_scale); TourEventNode.Attributes.Append(TourEventNode_toMSIPointX); TourEventNode.Attributes.Append(TourEventNode_toMSIPointY); TourEventNode.Attributes.Append(TourEventNode_duration); TLNode.AppendChild(TourEventNode); } else if (tourEvent.type == TourEvent.Type.fadeInMedia) { FadeInMediaEvent fadeInMediaEvent = (FadeInMediaEvent)tourEvent; XmlNode TourEventNode = doc.CreateElement("TourEvent"); XmlAttribute TourEventNode_beginTime = doc.CreateAttribute("beginTime"); XmlAttribute TourEventNode_type = doc.CreateAttribute("type"); XmlAttribute TourEventNode_toScreenPointX = doc.CreateAttribute("toScreenPointX"); XmlAttribute TourEventNode_toScreenPointY = doc.CreateAttribute("toScreenPointY"); XmlAttribute TourEventNode_scale = doc.CreateAttribute("scale"); XmlAttribute TourEventNode_duration = doc.CreateAttribute("duration"); TourEventNode_beginTime.Value = beginTime.ToString(); TourEventNode_type.Value = "FadeInMediaEvent"; TourEventNode_toScreenPointX.Value = fadeInMediaEvent.fadeInMediaToScreenPointX.ToString(); TourEventNode_toScreenPointY.Value = fadeInMediaEvent.fadeInMediaToScreenPointY.ToString(); TourEventNode_scale.Value = fadeInMediaEvent.absoluteScale.ToString(); TourEventNode_duration.Value = fadeInMediaEvent.duration.ToString(); TourEventNode.Attributes.Append(TourEventNode_beginTime); TourEventNode.Attributes.Append(TourEventNode_type); TourEventNode.Attributes.Append(TourEventNode_toScreenPointX); TourEventNode.Attributes.Append(TourEventNode_toScreenPointY); TourEventNode.Attributes.Append(TourEventNode_scale); TourEventNode.Attributes.Append(TourEventNode_duration); TLNode.AppendChild(TourEventNode); } else if (tourEvent.type == TourEvent.Type.fadeOutMedia) { FadeOutMediaEvent fadeOutMediaEvent = (FadeOutMediaEvent)tourEvent; XmlNode TourEventNode = doc.CreateElement("TourEvent"); XmlAttribute TourEventNode_beginTime = doc.CreateAttribute("beginTime"); XmlAttribute TourEventNode_type = doc.CreateAttribute("type"); XmlAttribute TourEventNode_duration = doc.CreateAttribute("duration"); TourEventNode_beginTime.Value = beginTime.ToString(); TourEventNode_type.Value = "FadeOutMediaEvent"; TourEventNode_duration.Value = fadeOutMediaEvent.duration.ToString(); TourEventNode.Attributes.Append(TourEventNode_beginTime); TourEventNode.Attributes.Append(TourEventNode_type); TourEventNode.Attributes.Append(TourEventNode_duration); TLNode.AppendChild(TourEventNode); } else if (tourEvent.type == TourEvent.Type.zoomMedia) { ZoomMediaEvent zoomMediaEvent = (ZoomMediaEvent)tourEvent; XmlNode TourEventNode = doc.CreateElement("TourEvent"); XmlAttribute TourEventNode_beginTime = doc.CreateAttribute("beginTime"); XmlAttribute TourEventNode_type = doc.CreateAttribute("type"); XmlAttribute TourEventNode_scale = doc.CreateAttribute("scale"); XmlAttribute TourEventNode_toScreenPointX = doc.CreateAttribute("toScreenPointX"); XmlAttribute TourEventNode_toScreenPointY = doc.CreateAttribute("toScreenPointY"); XmlAttribute TourEventNode_duration = doc.CreateAttribute("duration"); TourEventNode_beginTime.Value = beginTime.ToString(); TourEventNode_type.Value = "ZoomMediaEvent"; TourEventNode_scale.Value = zoomMediaEvent.absoluteScale.ToString(); TourEventNode_toScreenPointX.Value = zoomMediaEvent.zoomMediaToScreenPointX.ToString(); TourEventNode_toScreenPointY.Value = zoomMediaEvent.zoomMediaToScreenPointY.ToString(); TourEventNode_duration.Value = zoomMediaEvent.duration.ToString(); TourEventNode.Attributes.Append(TourEventNode_beginTime); TourEventNode.Attributes.Append(TourEventNode_type); TourEventNode.Attributes.Append(TourEventNode_scale); TourEventNode.Attributes.Append(TourEventNode_toScreenPointX); TourEventNode.Attributes.Append(TourEventNode_toScreenPointY); TourEventNode.Attributes.Append(TourEventNode_duration); TLNode.AppendChild(TourEventNode); } else if (tourEvent.type == TourEvent.Type.fadeInHighlight) { FadeInHighlightEvent fadeInHighlightEvent = (FadeInHighlightEvent)tourEvent; XmlNode TourEventNode = doc.CreateElement("TourEvent"); XmlAttribute TourEventNode_beginTime = doc.CreateAttribute("beginTime"); XmlAttribute TourEventNode_type = doc.CreateAttribute("type"); XmlAttribute TourEventNode_duration = doc.CreateAttribute("duration"); XmlAttribute TourEventNode_opacity = doc.CreateAttribute("opacity"); TourEventNode_beginTime.Value = beginTime.ToString(); TourEventNode_type.Value = "FadeInHighlightEvent"; TourEventNode_duration.Value = fadeInHighlightEvent.duration.ToString(); TourEventNode_opacity.Value = fadeInHighlightEvent.opacity.ToString(); TourEventNode.Attributes.Append(TourEventNode_beginTime); TourEventNode.Attributes.Append(TourEventNode_type); TourEventNode.Attributes.Append(TourEventNode_duration); TourEventNode.Attributes.Append(TourEventNode_opacity); TLNode.AppendChild(TourEventNode); } else if (tourEvent.type == TourEvent.Type.fadeOutHighlight) { FadeOutHighlightEvent fadeOutHighlightEvent = (FadeOutHighlightEvent)tourEvent; XmlNode TourEventNode = doc.CreateElement("TourEvent"); XmlAttribute TourEventNode_beginTime = doc.CreateAttribute("beginTime"); XmlAttribute TourEventNode_type = doc.CreateAttribute("type"); XmlAttribute TourEventNode_duration = doc.CreateAttribute("duration"); XmlAttribute TourEventNode_opacity = doc.CreateAttribute("opacity"); TourEventNode_beginTime.Value = beginTime.ToString(); TourEventNode_type.Value = "FadeOutHighlightEvent"; TourEventNode_duration.Value = fadeOutHighlightEvent.duration.ToString(); TourEventNode_opacity.Value = fadeOutHighlightEvent.opacity.ToString(); TourEventNode.Attributes.Append(TourEventNode_beginTime); TourEventNode.Attributes.Append(TourEventNode_type); TourEventNode.Attributes.Append(TourEventNode_duration); TourEventNode.Attributes.Append(TourEventNode_opacity); TLNode.AppendChild(TourEventNode); } else if (tourEvent.type == TourEvent.Type.fadeInPath) { FadeInPathEvent fadeInPathEvent = (FadeInPathEvent)tourEvent; XmlNode TourEventNode = doc.CreateElement("TourEvent"); XmlAttribute TourEventNode_beginTime = doc.CreateAttribute("beginTime"); XmlAttribute TourEventNode_type = doc.CreateAttribute("type"); XmlAttribute TourEventNode_duration = doc.CreateAttribute("duration"); TourEventNode_beginTime.Value = beginTime.ToString(); TourEventNode_type.Value = "FadeInPathEvent"; TourEventNode_duration.Value = fadeInPathEvent.duration.ToString(); TourEventNode.Attributes.Append(TourEventNode_beginTime); TourEventNode.Attributes.Append(TourEventNode_type); TourEventNode.Attributes.Append(TourEventNode_duration); TLNode.AppendChild(TourEventNode); } else if (tourEvent.type == TourEvent.Type.fadeOutPath) { FadeOutPathEvent fadeOutPathEvent = (FadeOutPathEvent)tourEvent; XmlNode TourEventNode = doc.CreateElement("TourEvent"); XmlAttribute TourEventNode_beginTime = doc.CreateAttribute("beginTime"); XmlAttribute TourEventNode_type = doc.CreateAttribute("type"); XmlAttribute TourEventNode_duration = doc.CreateAttribute("duration"); TourEventNode_beginTime.Value = beginTime.ToString(); TourEventNode_type.Value = "FadeOutPathEvent"; TourEventNode_duration.Value = fadeOutPathEvent.duration.ToString(); TourEventNode.Attributes.Append(TourEventNode_beginTime); TourEventNode.Attributes.Append(TourEventNode_type); TourEventNode.Attributes.Append(TourEventNode_duration); TLNode.AppendChild(TourEventNode); } } } else if (tourTL.type == TourTLType.audio) { XmlNode TLNode = doc.CreateElement("TourMediaTL"); XmlAttribute TLNode_type = doc.CreateAttribute("type"); XmlAttribute TLNode_displayName = doc.CreateAttribute("displayName"); XmlAttribute TLNode_file = doc.CreateAttribute("file"); XmlAttribute TLNode_beginTime = doc.CreateAttribute("beginTime"); XmlAttribute TLNode_duration = doc.CreateAttribute("duration"); TLNode_type.Value = tourTL.type.ToString(); TLNode_displayName.Value = tourTL.displayName; TLNode_file.Value = tourTL.file; TLNode_beginTime.Value = ((TourMediaTL)tourTL).BeginTime.Value.TotalSeconds.ToString(); TLNode_duration.Value = ((TourMediaTL)tourTL).Duration.TimeSpan.TotalSeconds.ToString(); TLNode.Attributes.Append(TLNode_type); TLNode.Attributes.Append(TLNode_displayName); TLNode.Attributes.Append(TLNode_file); TLNode.Attributes.Append(TLNode_beginTime); TLNode.Attributes.Append(TLNode_duration); tourNode.AppendChild(TLNode); } } doc.Save(xmlFileName); }
/// <summary> /// Sets a property value in a configuration file, creating the element if it does not already exist /// </summary> /// <param name="xmlDoc">The Xml document object</param> /// <param name="PropertyName">The name of the property to be set</param> /// <param name="NewValue">The new value for the property</param> /// <param name="ParentNode">The parent node of the property</param> /// <param name="XmlNodeName">The element name containing the key/value pair of attributes</param> /// <param name="NameAttribute">The Xml attribute name for the 'key'</param> /// <param name="ValueAttribute">The Xml attribute name for the 'value'</param> /// <returns>True if successful</returns> public static bool SetPropertyValue(XmlDocument xmlDoc, string PropertyName, string NewValue, XmlNode ParentNode, string XmlNodeName, string NameAttribute, string ValueAttribute) { string xPath = String.Format("{0}[@{1}='{2}']", XmlNodeName, NameAttribute, PropertyName); XmlNode n = ParentNode.SelectSingleNode(xPath); XmlAttribute att = null; if (n == null) { n = xmlDoc.CreateElement(XmlNodeName); att = xmlDoc.CreateAttribute(NameAttribute); att.Value = PropertyName; n.Attributes.Append(att); ParentNode.AppendChild(xmlDoc.CreateWhitespace(" ")); ParentNode.AppendChild(n); ParentNode.AppendChild(xmlDoc.CreateWhitespace("\r\n")); } att = n.Attributes[ValueAttribute]; if (att == null) { att = xmlDoc.CreateAttribute(ValueAttribute); n.Attributes.Append(att); } att.Value = NewValue; return true; }