public static void NameOfAllTypes() { var xmlDocument = new XmlDocument(); var element = xmlDocument.CreateElement("newElem"); Assert.Equal("newElem", element.Name); var attribute = xmlDocument.CreateAttribute("newAttr"); Assert.Equal("newAttr", attribute.Name); var text = xmlDocument.CreateTextNode(""); Assert.Equal("#text", text.Name); var cdata = xmlDocument.CreateCDataSection(""); Assert.Equal("#cdata-section", cdata.Name); var pi = xmlDocument.CreateProcessingInstruction("PI", ""); Assert.Equal("PI", pi.Name); var comment = xmlDocument.CreateComment("some text"); Assert.Equal("#comment", comment.Name); var fragment = xmlDocument.CreateDocumentFragment(); Assert.Equal("#document-fragment", fragment.Name); }
public static void CreateEmptyComment() { var xmlDocument = new XmlDocument(); var comment = xmlDocument.CreateComment(String.Empty); Assert.Equal("<!---->", comment.OuterXml); Assert.Equal(String.Empty, comment.InnerText); Assert.Equal(comment.NodeType, XmlNodeType.Comment); }
public static void ImportDocumentFragment() { var tempDoc = new XmlDocument(); var nodeToImport = tempDoc.CreateDocumentFragment(); nodeToImport.AppendChild(tempDoc.CreateElement("A1")); nodeToImport.AppendChild(tempDoc.CreateComment("comment")); nodeToImport.AppendChild(tempDoc.CreateProcessingInstruction("PI", "donothing")); var xmlDocument = new XmlDocument(); var node = xmlDocument.ImportNode(nodeToImport, true); Assert.Equal(xmlDocument, node.OwnerDocument); Assert.Equal(XmlNodeType.DocumentFragment, node.NodeType); Assert.Equal(nodeToImport.OuterXml, node.OuterXml); }
public static void OwnerDocumentOnImportedTree() { var tempDoc = new XmlDocument(); var nodeToImport = tempDoc.CreateDocumentFragment(); nodeToImport.AppendChild(tempDoc.CreateElement("A1")); nodeToImport.AppendChild(tempDoc.CreateComment("comment")); nodeToImport.AppendChild(tempDoc.CreateProcessingInstruction("PI", "donothing")); var xmlDocument = new XmlDocument(); var node = xmlDocument.ImportNode(nodeToImport, true); Assert.Equal(xmlDocument, node.OwnerDocument); foreach (XmlNode child in node.ChildNodes) Assert.Equal(xmlDocument, child.OwnerDocument); }
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 WritePropertyXML() { string fileLocation = HttpContext.Current.Server.MapPath("Output") + "\\"; try { ClearXMLDirectory(fileLocation); ArrayList skipList = new ArrayList(); GetPrimaryKeyFields(WrapperAppParams.TableName, ref skipList); GetColumnType(WrapperAppParams.TableName, ref skipList); string query = "select * from " + WrapperAppParams.TableName + " where "; string[] pkFieldList = WrapperAppParams.FieldNames.Split(';'); string[] pkFieldValues = WrapperAppParams.FieldValues.Split(';'); for (int k = 0; k < pkFieldList.Length; k++) { query += " \"" + pkFieldList[k] + "\"='" + pkFieldValues[k] + "'"; if (k < pkFieldList.Length - 1) { query += " AND "; } } NpgsqlConnection dbConnection = new NpgsqlConnection(); dbConnection.ConnectionString = CommonFunctions.GetWrapperConenctionString(); dbConnection.Open(); DataTable dtValues = GetDataTable(query, dbConnection); XmlDocument xml = new XmlDocument(); XmlElement root = xml.CreateElement("CAD"); xml.AppendChild(root); XmlComment comment = xml.CreateComment("config values"); root.AppendChild(comment); XmlElement connectionString = xml.CreateElement("connectionString"); connectionString.InnerText = CommonFunctions.GetConnectionString(); root.AppendChild(connectionString); XmlElement wrapperConnectionString = xml.CreateElement("wrapperConnectionString"); wrapperConnectionString.InnerText = CommonFunctions.GetWrapperConenctionString(); root.AppendChild(wrapperConnectionString); XmlElement metaTable = xml.CreateElement("metaTable"); metaTable.InnerText = CommonFunctions.GetMetaTableName(); root.AppendChild(metaTable); //XmlElement metaTableStorage = xml.CreateElement("metadataStorage"); //metaTableStorage.InnerText = CommonFunctions.GetMetaDataStorageName(); //root.AppendChild(metaTableStorage); XmlElement activeDatabase = xml.CreateElement("activeDatabase"); activeDatabase.InnerText = CommonFunctions.GetActiveDatabaseName(); root.AppendChild(activeDatabase); comment = xml.CreateComment("field-value pair below"); root.AppendChild(comment); XmlElement group = xml.CreateElement("group"); group.InnerText = WrapperAppParams.GroupName; root.AppendChild(group); DataRow dtRow = dtValues.Rows[0]; foreach (DataColumn col in dtValues.Columns) { XmlElement field = xml.CreateElement("field"); XmlElement name = xml.CreateElement("name"); if (!skipList.Contains(col.ColumnName)) { name.InnerText = col.ColumnName; XmlElement value = xml.CreateElement("value"); if (col.DataType.Name == "DateTime") { string date = ""; try { date = Convert.ToDateTime(dtRow[col.ColumnName]).ToString("dd-MM-yyyy"); } catch { } finally { value.InnerText = date; } } else { value.InnerText = dtRow[col.ColumnName].ToString(); } field.AppendChild(name); field.AppendChild(value); root.AppendChild(field); } } System.IO.StreamWriter sw = new System.IO.StreamWriter(fileLocation + WrapperAppParams.FileName, false); sw.WriteLine(xml.InnerXml); sw.Close(); dbConnection.Close(); dtValues.Dispose(); } catch (Exception exp) { File.Delete(fileLocation + WrapperAppParams.FileName); throw exp; } }
public static void InsertCommentNodeToDocument() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<root/>"); var node = xmlDocument.CreateComment("some comment"); Assert.Equal(0, xmlDocument.DocumentElement.ChildNodes.Count); var result = xmlDocument.DocumentElement.InsertBefore(node, null); Assert.Same(node, result); Assert.Equal(1, xmlDocument.DocumentElement.ChildNodes.Count); }
public virtual bool Construct(ref XmlDocument Map) { var Constructed = true; try { XmlNode Node; var Doc = new XmlDocument(); Node = Doc.CreateXmlDeclaration("1.0", "utf-8", string.Empty); Doc.AppendChild(Node); Node = Doc.CreateComment(string.Format(" ScpMapper Configuration Data. {0} ", DateTime.Now)); Doc.AppendChild(Node); Node = Doc.CreateNode(XmlNodeType.Element, "ScpMapper", null); { CreateTextNode(Doc, Node, "Description", "SCP Mapping File"); CreateTextNode(Doc, Node, "Version", Assembly.GetExecutingAssembly().GetName().Version.ToString()); var Mapping = Doc.CreateNode(XmlNodeType.Element, "Mapping", null); { foreach (var Item in m_Mapper.Values) { if (Item.Default) { CreateTextNode(Doc, Node, "Active", Item.Name); } var Profile = Doc.CreateNode(XmlNodeType.Element, "Profile", null); { CreateTextNode(Doc, Profile, "Name", Item.Name); CreateTextNode(Doc, Profile, "Type", Item.Type); CreateTextNode(Doc, Profile, "Value", Item.Qualifier); var Ds3 = Doc.CreateNode(XmlNodeType.Element, DsModel.DS3.ToString(), null); { var Button = Doc.CreateNode(XmlNodeType.Element, "Button", null); { foreach (var Ds3Button in Item.Ds3Button.Keys) { CreateTextNode(Doc, Button, Ds3Button.ToString(), Item.Ds3Button[Ds3Button].ToString()); } } Ds3.AppendChild(Button); var Axis = Doc.CreateNode(XmlNodeType.Element, "Axis", null); { foreach (var Ds3Axis in Item.Ds3Axis.Keys) { CreateTextNode(Doc, Axis, Ds3Axis.ToString(), Item.Ds3Axis[Ds3Axis].ToString()); } } Ds3.AppendChild(Axis); } Profile.AppendChild(Ds3); var Ds4 = Doc.CreateNode(XmlNodeType.Element, DsModel.DS4.ToString(), null); { var Button = Doc.CreateNode(XmlNodeType.Element, "Button", null); { foreach (var Ds4Button in Item.Ds4Button.Keys) { CreateTextNode(Doc, Button, Ds4Button.ToString(), Item.Ds4Button[Ds4Button].ToString()); } } Ds4.AppendChild(Button); var Axis = Doc.CreateNode(XmlNodeType.Element, "Axis", null); { foreach (var Ds4Axis in Item.Ds4Axis.Keys) { CreateTextNode(Doc, Axis, Ds4Axis.ToString(), Item.Ds4Axis[Ds4Axis].ToString()); } } Ds4.AppendChild(Axis); } Profile.AppendChild(Ds4); } Mapping.AppendChild(Profile); } } Node.AppendChild(Mapping); } Doc.AppendChild(Node); Map = Doc; } catch (Exception ex) { Log.ErrorFormat("Unexpected error: {0}", ex); Constructed = false; } return(Constructed); }
public static void AddComment(XmlDocument doc, XmlElement nodeParent, String comment) { XmlNode commentnode = doc.CreateComment(comment); nodeParent.AppendChild(commentnode); }
/// <summary> /// Recursively called method that clones source nodes into nodes in the destination /// document. /// </summary> private void CloneChildrenResolvingImports(XmlNode source, XmlNode destination) { XmlDocument sourceDocument = source.OwnerDocument ?? (XmlDocument)source; XmlDocument destinationDocument = destination.OwnerDocument ?? (XmlDocument)destination; foreach (XmlNode child in source.ChildNodes) { // Only one of <?xml version="1.0" encoding="utf-16"?> and we got it automatically already if (child.NodeType == XmlNodeType.XmlDeclaration) { continue; } // If this is not the first <Project> tag if ( child.NodeType == XmlNodeType.Element && sourceDocument.DocumentElement == child && // This is the root element, not some random element named 'Project' destinationDocument.DocumentElement != null && // Skip <Project> tag from the outer project String.Equals(XMakeElements.project, child.Name, StringComparison.Ordinal) ) { // But suffix any InitialTargets attribute string outerInitialTargets = destinationDocument.DocumentElement.GetAttribute(XMakeAttributes.initialTargets).Trim(); string innerInitialTargets = ((XmlElement)child).GetAttribute(XMakeAttributes.initialTargets).Trim(); if (innerInitialTargets.Length > 0) { if (outerInitialTargets.Length > 0) { outerInitialTargets += ";"; } destinationDocument.DocumentElement.SetAttribute(XMakeAttributes.initialTargets, outerInitialTargets + innerInitialTargets); } // Also gather any DefaultTargets value if none has been encountered already; put it on the outer <Project> tag string outerDefaultTargets = destinationDocument.DocumentElement.GetAttribute(XMakeAttributes.defaultTargets).Trim(); if (outerDefaultTargets.Length == 0) { string innerDefaultTargets = ((XmlElement)child).GetAttribute(XMakeAttributes.defaultTargets).Trim(); if (innerDefaultTargets.Trim().Length > 0) { destinationDocument.DocumentElement.SetAttribute(XMakeAttributes.defaultTargets, innerDefaultTargets); } } // Add any implicit imports for an imported document AddImplicitImportNodes(child.OwnerDocument.DocumentElement); CloneChildrenResolvingImports(child, destination); continue; } // Resolve <Import> to 0-n documents and walk into them if (child.NodeType == XmlNodeType.Element && String.Equals(XMakeElements.import, child.Name, StringComparison.Ordinal)) { // To display what the <Import> tag looked like string importCondition = ((XmlElement)child).GetAttribute(XMakeAttributes.condition); string condition = importCondition.Length > 0 ? $" Condition=\"{importCondition}\"" : String.Empty; string importProject = ((XmlElement)child).GetAttribute(XMakeAttributes.project).Replace("--", "__"); string importSdk = ((XmlElement)child).GetAttribute(XMakeAttributes.sdk); string sdk = importSdk.Length > 0 ? $" {XMakeAttributes.sdk}=\"{importSdk}\"" : String.Empty; // Get the Sdk attribute of the Project element if specified string projectSdk = source.NodeType == XmlNodeType.Element && String.Equals(XMakeElements.project, source.Name, StringComparison.Ordinal) ? ((XmlElement)source).GetAttribute(XMakeAttributes.sdk) : String.Empty; IList <ProjectRootElement> resolvedList; if (!_importTable.TryGetValue((XmlElement)child, out resolvedList)) { // Import didn't resolve to anything; just display as a comment and move on string closedImportTag = $"<Import Project=\"{importProject}\"{sdk}{condition} />"; destination.AppendChild(destinationDocument.CreateComment(closedImportTag)); continue; } for (int i = 0; i < resolvedList.Count; i++) { ProjectRootElement resolved = resolvedList[i]; XmlDocument innerDocument = resolved.XmlDocument; string importTag = $" <Import Project=\"{importProject}\"{sdk}{condition}>"; if (!String.IsNullOrWhiteSpace(importSdk) && projectSdk.IndexOf(importSdk, StringComparison.OrdinalIgnoreCase) >= 0) { importTag += $"\r\n This import was added implicitly because the {XMakeElements.project} element's {XMakeAttributes.sdk} attribute specified \"{importSdk}\"."; } destination.AppendChild(destinationDocument.CreateComment( $"\r\n{new String('=', 140)}\r\n{importTag}\r\n\r\n{resolved.FullPath.Replace("--", "__")}\r\n{new String('=', 140)}\r\n")); _filePaths.Push(resolved.FullPath); CloneChildrenResolvingImports(innerDocument, destination); _filePaths.Pop(); if (i < resolvedList.Count - 1) { destination.AppendChild(destinationDocument.CreateComment("\r\n" + new String('=', 140) + "\r\n </Import>\r\n" + new String('=', 140) + "\r\n")); } else { destination.AppendChild(destinationDocument.CreateComment("\r\n" + new String('=', 140) + "\r\n </Import>\r\n\r\n" + _filePaths.Peek()?.Replace("--", "__") + "\r\n" + new String('=', 140) + "\r\n")); } } continue; } // Skip over <ImportGroup> into its children if (child.NodeType == XmlNodeType.Element && String.Equals(XMakeElements.importGroup, child.Name, StringComparison.Ordinal)) { // To display what the <ImportGroup> tag looked like string importGroupCondition = ((XmlElement)child).GetAttribute(XMakeAttributes.condition); string importGroupTag = "<ImportGroup" + ((importGroupCondition.Length > 0) ? " Condition=\"" + importGroupCondition + "\"" : String.Empty) + ">"; destination.AppendChild(destinationDocument.CreateComment(importGroupTag)); CloneChildrenResolvingImports(child, destination); destination.AppendChild(destinationDocument.CreateComment("</" + XMakeElements.importGroup + ">")); continue; } // Node doesn't need special treatment, clone and append XmlNode clone = destinationDocument.ImportNode(child, false /* shallow */); // ImportNode does a clone but unlike CloneNode it works across XmlDocuments if (clone.NodeType == XmlNodeType.Element && String.Equals(XMakeElements.project, child.Name, StringComparison.Ordinal) && clone.Attributes?[XMakeAttributes.sdk] != null) { clone.Attributes.Remove(clone.Attributes[XMakeAttributes.sdk]); } destination.AppendChild(clone); CloneChildrenResolvingImports(child, clone); } }
public XmlNode exportXMLnode() { XmlDocument xmlDoc = new XmlDocument(); StringWriter stringWriter = new StringWriter(); XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter); XmlNode rootNode = null; if (isNodeComment) { rootNode = xmlDoc.CreateComment(comment); xmlDoc.AppendChild(rootNode); return(rootNode); } rootNode = xmlDoc.CreateElement(domnType.ToString()); xmlDoc.AppendChild(rootNode); #region IEC61850Server if (slaveType == SlaveTypes.IEC61850Server) { foreach (string attr in arrAttributes) { XmlAttribute attrName = xmlDoc.CreateAttribute(attr); attrName.Value = (string)this.GetType().GetProperty(attr).GetValue(this); rootNode.Attributes.Append(attrName); } XmlAttribute attr2 = xmlDoc.CreateAttribute("ReportingIndex"); attr2.Value = iec61850reportingindex.ToString(); rootNode.Attributes.Append(attr2); XmlAttribute attrDataType = xmlDoc.CreateAttribute("DataType"); attrDataType.Value = DataType.ToString(); rootNode.Attributes.Append(attrDataType); XmlAttribute attrCommandType = xmlDoc.CreateAttribute("CommandType"); attrCommandType.Value = CommandType.ToString(); rootNode.Attributes.Append(attrCommandType); XmlAttribute attrDeadband = xmlDoc.CreateAttribute("BitPos"); attrDeadband.Value = BitPos.ToString(); rootNode.Attributes.Append(attrDeadband); XmlAttribute attrConstant = xmlDoc.CreateAttribute("Description"); attrConstant.Value = Description.ToString(); rootNode.Attributes.Append(attrConstant); } #endregion IEC61850Server if ((slaveType == SlaveTypes.DNP3SLAVE) || (slaveType == SlaveTypes.IEC101SLAVE) || (slaveType == SlaveTypes.SPORTSLAVE) || (slaveType == SlaveTypes.IEC104) || (slaveType == SlaveTypes.MODBUSSLAVE) || (slaveType == SlaveTypes.UNKNOWN) || (slaveType == SlaveTypes.MQTTSLAVE) || (slaveType == SlaveTypes.SMSSLAVE)) { foreach (string attr in arrAttributes) { XmlAttribute attrName = xmlDoc.CreateAttribute(attr); attrName.Value = (string)this.GetType().GetProperty(attr).GetValue(this); rootNode.Attributes.Append(attrName); } } #region GDisplaySlave if (slaveType == SlaveTypes.GRAPHICALDISPLAYSLAVE) { foreach (string attr in arrAttributes) { XmlAttribute attrName = xmlDoc.CreateAttribute(attr); attrName.Value = (string)this.GetType().GetProperty(attr).GetValue(this); rootNode.Attributes.Append(attrName); } XmlAttribute attrCellNo = xmlDoc.CreateAttribute("CellNo"); attrCellNo.Value = CellNo.ToString(); rootNode.Attributes.Append(attrCellNo); XmlAttribute attrWidget = xmlDoc.CreateAttribute("Widget"); attrWidget.Value = Widget.ToString(); rootNode.Attributes.Append(attrWidget); //XmlAttribute attrUnit = xmlDoc.CreateAttribute("Unit"); //attrUnit.Value = UnitID.ToString(); //rootNode.Attributes.Append(attrUnit); XmlAttribute attrDescription = xmlDoc.CreateAttribute("Description"); attrDescription.Value = Description.ToString(); rootNode.Attributes.Append(attrDescription); } #endregion GDisplaySlave return(rootNode); }
/// <summary> /// Saves the texture pack (texture + swatches + xml manifest) /// </summary> /// <param name="_FileName"></param> public void SavePack(System.IO.FileInfo _FileName, TARGET_FORMAT _TargetFormat) { if (m_Texture == null) { throw new Exception("No calibrated texture has been built! Can't save."); } System.IO.DirectoryInfo Dir = _FileName.Directory; string RawFileName = System.IO.Path.GetFileNameWithoutExtension(_FileName.FullName); string Extension = System.IO.Path.GetExtension(_FileName.FullName); System.IO.FileInfo FileName_Manifest = new System.IO.FileInfo(System.IO.Path.Combine(Dir.FullName, RawFileName + ".xml")); System.IO.FileInfo FileName_SwatchMin = new System.IO.FileInfo(System.IO.Path.Combine(Dir.FullName, RawFileName + "_Min" + Extension)); System.IO.FileInfo FileName_SwatchMax = new System.IO.FileInfo(System.IO.Path.Combine(Dir.FullName, RawFileName + "_Max" + Extension)); System.IO.FileInfo FileName_SwatchAvg = new System.IO.FileInfo(System.IO.Path.Combine(Dir.FullName, RawFileName + "_Avg" + Extension)); System.IO.FileInfo[] FileName_CustomSwatches = new System.IO.FileInfo[m_CustomSwatches.Length]; for (int CustomSwatchIndex = 0; CustomSwatchIndex < m_CustomSwatches.Length; CustomSwatchIndex++) { FileName_CustomSwatches[CustomSwatchIndex] = new System.IO.FileInfo(System.IO.Path.Combine(Dir.FullName, RawFileName + "_Custom" + CustomSwatchIndex.ToString() + Extension)); } ////////////////////////////////////////////////////////////////////////// // Build image type and format parameters as well as target color profile ImageUtility.Bitmap.FILE_TYPE FileType = ImageUtility.Bitmap.FILE_TYPE.UNKNOWN; ImageUtility.Bitmap.FORMAT_FLAGS Format = ImageUtility.Bitmap.FORMAT_FLAGS.NONE; switch (_TargetFormat) { case TARGET_FORMAT.PNG8: FileType = ImageUtility.Bitmap.FILE_TYPE.PNG; Format = ImageUtility.Bitmap.FORMAT_FLAGS.SAVE_8BITS_UNORM; break; case TARGET_FORMAT.PNG16: FileType = ImageUtility.Bitmap.FILE_TYPE.PNG; Format = ImageUtility.Bitmap.FORMAT_FLAGS.SAVE_16BITS_UNORM; break; case TARGET_FORMAT.TIFF: FileType = ImageUtility.Bitmap.FILE_TYPE.TIFF; Format = ImageUtility.Bitmap.FORMAT_FLAGS.SAVE_16BITS_UNORM; break; } if (FileType == ImageUtility.Bitmap.FILE_TYPE.UNKNOWN) { throw new Exception("Unknown target file format!"); } ////////////////////////////////////////////////////////////////////////// // Save textures // Save main texture SaveImage(m_Texture, _FileName, FileType, Format); // Save default swatches SaveImage(m_SwatchMin.Texture, FileName_SwatchMin, FileType, Format); SaveImage(m_SwatchMax.Texture, FileName_SwatchMax, FileType, Format); SaveImage(m_SwatchAvg.Texture, FileName_SwatchAvg, FileType, Format); // Save custom swatches for (int CustomSwatchIndex = 0; CustomSwatchIndex < m_CustomSwatches.Length; CustomSwatchIndex++) { SaveImage(m_CustomSwatches[CustomSwatchIndex].Texture, FileName_CustomSwatches[CustomSwatchIndex], FileType, Format); } ////////////////////////////////////////////////////////////////////////// // Prepare the XML manifest XmlDocument Doc = new XmlDocument(); XmlComment HeaderComment = Doc.CreateComment( "***Do not modify!***\r\n\r\n" + "This is a calibrated texture manifest file generated from the uncalibrated image \"" + m_CaptureParameters.SourceImageName + "\"\r\n" + "Resulting generated images have been stored using a standard sRGB profile and can be used directly as source or color-picked by artists\r\n" + " without any other processing. Colors in the textures will have the proper reflectance (assuming the original image has been properly captured\r\n" + " with specular removal using polarization filters) and after sRGB->Linear conversion will be directly useable as reflectance in the lighting equation.\r\n" + "The xyY values are given in device-independent xyY color space and can be used as linear-space colors directly.\r\n\r\n" + "***Do not modify!***"); Doc.AppendChild(HeaderComment); XmlElement Root = Doc.CreateElement("Manifest"); Doc.AppendChild(Root); // Save source image infos XmlElement SourceInfosElement = AppendElement(Root, "SourceInfos"); SetAttribute(AppendElement(SourceInfosElement, "SourceImageName"), "Value", m_CaptureParameters.SourceImageName); SetAttribute(AppendElement(SourceInfosElement, "ISOSpeed"), "Value", m_CaptureParameters.ISOSpeed.ToString()); SetAttribute(AppendElement(SourceInfosElement, "ShutterSpeed"), "Value", m_CaptureParameters.ShutterSpeed.ToString()); SetAttribute(AppendElement(SourceInfosElement, "Aperture"), "Value", m_CaptureParameters.Aperture.ToString()); SetAttribute(AppendElement(SourceInfosElement, "SpatialCorrection"), "Status", m_SpatialCorrectionEnabled ? "Enabled" : "Disabled"); SetAttribute(AppendElement(SourceInfosElement, "WhiteReflectanceCorrectionFactor"), "Value", m_WhiteReflectanceCorrectionFactor.ToString()); if (m_WhiteReflectanceReference.z > 0.0f) { SetAttribute(AppendElement(SourceInfosElement, "WhiteBalance"), "xyY", m_WhiteReflectanceReference.ToString()); } SetAttribute(AppendElement(SourceInfosElement, "CropSource"), "Value", m_CaptureParameters.CropSource.ToString()); SetAttribute(AppendElement(SourceInfosElement, "CropRectangleCenter"), "X", m_CaptureParameters.CropRectangleCenter.x.ToString()).SetAttribute("Y", m_CaptureParameters.CropRectangleCenter.y.ToString()); SetAttribute(AppendElement(SourceInfosElement, "CropRectangleHalfSize"), "X", m_CaptureParameters.CropRectangleHalfSize.x.ToString()).SetAttribute("Y", m_CaptureParameters.CropRectangleHalfSize.y.ToString()); SetAttribute(AppendElement(SourceInfosElement, "CropRectangleRotation"), "Value", m_CaptureParameters.CropRectangleRotation.ToString()); SetAttribute(AppendElement(SourceInfosElement, "SwatchesSize"), "Width", m_SwatchWidth.ToString()).SetAttribute("Height", m_SwatchHeight.ToString()); SetAttribute(AppendElement(SourceInfosElement, "TargetFormat"), "Value", _TargetFormat.ToString()); // Save calibrated texture infos { XmlElement CalibratedTextureElement = AppendElement(Root, "CalibratedTexture"); SetAttribute(CalibratedTextureElement, "Name", _FileName.Name).SetAttribute("Width", m_Texture.Width.ToString()).SetAttribute("Height", m_Texture.Height.ToString()); // Save default swatches XmlElement DefaultSwatchesElement = AppendElement(CalibratedTextureElement, "DefaultSwatches"); XmlElement MinSwatchElement = AppendElement(DefaultSwatchesElement, "Min"); SetAttribute(MinSwatchElement, "Name", FileName_SwatchMin.Name); m_SwatchMin.Save(this, MinSwatchElement); XmlElement MaxSwatchElement = AppendElement(DefaultSwatchesElement, "Max"); SetAttribute(MaxSwatchElement, "Name", FileName_SwatchMax.Name); m_SwatchMax.Save(this, MaxSwatchElement); XmlElement AvgSwatchElement = AppendElement(DefaultSwatchesElement, "Avg"); SetAttribute(AvgSwatchElement, "Name", FileName_SwatchAvg.Name); m_SwatchAvg.Save(this, AvgSwatchElement); } // Save custom swatches infos if (m_CustomSwatches.Length > 0) { XmlElement CustomSwatchesElement = AppendElement(Root, "CustomSwatches"); SetAttribute(CustomSwatchesElement, "Count", m_CustomSwatches.Length.ToString()); for (int CustomSwatchIndex = 0; CustomSwatchIndex < m_CustomSwatches.Length; CustomSwatchIndex++) { XmlElement CustomSwatchElement = AppendElement(CustomSwatchesElement, "Custom" + CustomSwatchIndex.ToString()); SetAttribute(CustomSwatchElement, "Name", FileName_CustomSwatches[CustomSwatchIndex].Name); m_CustomSwatches[CustomSwatchIndex].Save(this, CustomSwatchElement); } } Doc.Save(FileName_Manifest.FullName); }
private void FillFileDescriptions() { XmlElement root = _ormXmlDocumentMain.DocumentElement; if (!string.IsNullOrEmpty(_model.Namespace)) { root.SetAttribute("defaultNamespace", _model.Namespace); } if (!string.IsNullOrEmpty(_model.SchemaVersion)) { root.SetAttribute("schemaVersion", _model.SchemaVersion); } if (!string.IsNullOrEmpty(_model.EntityBaseTypeName)) { root.SetAttribute("entityBaseType", _model.EntityBaseTypeName); } if (_model.EnableCommonPropertyChangedFire) { root.SetAttribute("enableCommonPropertyChangedFire", XmlConvert.ToString(_model.EnableCommonPropertyChangedFire)); } //if (!_model.GenerateEntityName) // root.SetAttribute("generateEntityName", // XmlConvert.ToString(_model.GenerateEntityName)); if (_model.GenerateMode != GenerateModeEnum.Full) { root.SetAttribute("generateMode", _model.GenerateMode.ToString()); } if (_model.AddVersionToSchemaName) { root.SetAttribute("addVersionToSchemaName", "true"); } if (_model.GenerateSingleFile) { root.SetAttribute("singleFile", "true"); } StringBuilder commentBuilder = new StringBuilder(); foreach (string comment in _model.SystemComments) { commentBuilder.AppendLine(comment); } if (_model.UserComments.Count > 0) { commentBuilder.AppendLine(); foreach (string comment in _model.UserComments) { commentBuilder.AppendLine(comment); } } XmlComment commentsElement = _ormXmlDocumentMain.CreateComment(commentBuilder.ToString()); _ormXmlDocumentMain.InsertBefore(commentsElement, root); }
private void button1_Click(object sender, EventArgs e) { //Create an xml document doc = new XmlDocument(); //If there is no current file, then create a new one if (!System.IO.File.Exists(PATH)) { //Create neccessary nodes XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "UTF-8", "yes"); XmlComment comment = doc.CreateComment("This is an XML Generated File"); XmlElement root = doc.CreateElement("servers"); XmlElement server = doc.CreateElement("server"); // XmlAttribute sql = doc.CreateAttribute("sql"); XmlElement svr_name = doc.CreateElement("svr_name"); XmlElement db_name = doc.CreateElement("db_name"); XmlElement db_login = doc.CreateElement("db_login"); XmlElement db_passWord = doc.CreateElement("db_passWord"); //Add the values for each nodes // sql.Value = textBox1.Text; svr_name.InnerText = txtSRVName.Text; db_name.InnerText = txtDBName.Text; db_login.InnerText = txtLogin.Text; db_passWord.InnerText = StringCipher.Encrypt(txtPassWord.Text, "9ge340");// Encrypt(txtPassWord.Text, true);// txtPassWord.Text; //Construct the document doc.AppendChild(declaration); doc.AppendChild(comment); doc.AppendChild(root); root.AppendChild(server); // server.Attributes.Append(sql); server.AppendChild(svr_name); server.AppendChild(db_name); server.AppendChild(db_login); server.AppendChild(db_passWord); doc.Save(PATH); } else //If there is already a file { //Load the XML File doc.Load(PATH); //Get the root element XmlElement root = doc.DocumentElement; XmlElement server = doc.CreateElement("server"); XmlElement srv_name = doc.CreateElement("srv_name"); XmlElement db_name = doc.CreateElement("db_name"); //XmlElement gender = doc.CreateElement("Gender"); XmlElement db_login = doc.CreateElement("db_login"); XmlElement db_passWord = doc.CreateElement("db_passWord"); //Add the values for each nodes srv_name.InnerText = txtSRVName.Text; db_name.InnerText = txtDBName.Text; //gender.InnerText = textBox2.Text; db_login.InnerText = txtLogin.Text; db_passWord.InnerText = Encrypt(txtPassWord.Text, "9ge340");// StringCipher.Decrypt(txtPassWord.Text, txtPassWord.Text);// Encrypt(txtPassWord.Text, true);// txtPassWord.Text; //Construct the Person element server.AppendChild(srv_name); server.AppendChild(db_name); server.AppendChild(db_login); server.AppendChild(db_passWord); //person.AppendChild(gender); //Add the New person element to the end of the root element root.AppendChild(server); //Save the document doc.Save(PATH); } //Show confirmation message try { using (SqlConnection con = new SqlConnection(da.GetConnectionString())) { SqlCommand command = new SqlCommand(); con.Open(); con.Close(); // this.Hide(); //Form1 Form1 = new Form1();// نمایش فرم تنظیمات ////Form1.Show(); var msg = " اتصال به بانک با موفقیت انجام شد. "; MessageForm.Show(msg, "اتصال به بانک", MessageFormIcons.Info, MessageFormButtons.Ok, color); connected = true; txtDBName.Enabled = txtLogin.Enabled = txtSRVName.Enabled = txtPassWord.Enabled = button2.Enabled = button1.Enabled = false; button3.BackColor = Color.White; button3.BackColor = color; button3.BackColor = Color.White; button3.BackColor = color; //this.Close(); } } catch { var msg = "اطلاعات اتصال به بانک درست نمی باشد. "; MessageForm.Show(msg, "خطا در اتصال به بانک", MessageFormIcons.Warning, MessageFormButtons.Ok, color); //this.Close(); } //MessageBox.Show("Details have been added to the XML File."); //Reset text fields for new input //txtSRVName.Text = String.Empty; //txtDBName.Text = String.Empty; //textBoxGender.Text = String.Empty; }
private static XmlElement GetRequestedPrivilegeElement(XmlElement inputRequestedPrivilegeElement, XmlDocument document) { // <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3"> // <!-- // UAC Manifest Options // If you want to change the Windows User Account Control level replace the // requestedExecutionLevel node with one of the following . // <requestedExecutionLevel level="asInvoker" /> // <requestedExecutionLevel level="requireAdministrator" /> // <requestedExecutionLevel level="highestAvailable" /> // If you want to utilize File and Registry Virtualization for backward compatibility // delete the requestedExecutionLevel node. // --> // <requestedExecutionLevel level="asInvoker" /> // </requestedPrivileges> // we always create a requestedPrivilege node to put into the generated TrustInfo document // XmlElement requestedPrivilegeElement = document.CreateElement(XmlUtil.TrimPrefix(XPaths.requestedPrivilegeElement), XmlNamespaces.asmv3); document.AppendChild(requestedPrivilegeElement); // our three cases we need to handle are: // (a) no requestedPrivilege node (and therefore no requestedExecutionLevel node as well) - use default values // (b) requestedPrivilege node and no requestedExecutionLevel node - omit the requestedExecutionLevel node // (c) requestedPrivilege node and requestedExecutionLevel node - use the incoming requestedExecutionLevel node values // // using null for both values is case (b) above -- do not output values // string executionLevelString = null; string executionUIAccessString = null; string commentString = null; // case (a) above -- load default values // if (inputRequestedPrivilegeElement == null) { // If UAC requestedPrivilege node is missing (possibly due to upgraded project) then automatically // add a default UAC requestedPrivilege node with a default requestedExecutionLevel node set to // the expected ClickOnce level (asInvoker) with uiAccess as false // executionLevelString = Constants.UACAsInvoker; executionUIAccessString = Constants.UACUIAccess; // load up a default comment string that we put in front of the requestedExecutionLevel node // here so we can allow the passed-in node to override it if there is a comment present // System.Resources.ResourceManager resources = new System.Resources.ResourceManager("Microsoft.Build.Tasks.Core.Strings.ManifestUtilities", typeof(SecurityUtilities).Module.Assembly); commentString = resources.GetString("TrustInfo.RequestedExecutionLevelComment"); } else { // we need to see if the requestedExecutionLevel node is present to decide whether or not to create one. // XmlNamespaceManager nsmgr = XmlNamespaces.GetNamespaceManager(document.NameTable); XmlElement inputRequestedExecutionLevel = (XmlElement)inputRequestedPrivilegeElement.SelectSingleNode(XPaths.requestedExecutionLevelElement, nsmgr); // case (c) above -- use incoming values [note that we should do nothing for case (b) above // because the default values will make us not emit the requestedExecutionLevel and comment] // if (inputRequestedExecutionLevel != null) { XmlNode previousNode = inputRequestedExecutionLevel.PreviousSibling; // fetch the current comment node if there is one (if there is not one, simply // keep the default null value which means we will not create one in the // output document) // if (previousNode?.NodeType == XmlNodeType.Comment) { commentString = ((XmlComment)previousNode).Data; } // fetch the current requestedExecutionLevel node's level attribute if there is one // if (inputRequestedExecutionLevel.HasAttribute("level")) { executionLevelString = inputRequestedExecutionLevel.GetAttribute("level"); } // fetch the current requestedExecutionLevel node's uiAccess attribute if there is one // if (inputRequestedExecutionLevel.HasAttribute("uiAccess")) { executionUIAccessString = inputRequestedExecutionLevel.GetAttribute("uiAccess"); } } } if (commentString != null) { XmlComment requestedPrivilegeComment = document.CreateComment(commentString); requestedPrivilegeElement.AppendChild(requestedPrivilegeComment); } if (executionLevelString != null) { XmlElement requestedExecutionLevelElement = document.CreateElement(XmlUtil.TrimPrefix(XPaths.requestedExecutionLevelElement), XmlNamespaces.asmv3); requestedPrivilegeElement.AppendChild(requestedExecutionLevelElement); XmlAttribute levelAttribute = document.CreateAttribute("level"); levelAttribute.Value = executionLevelString; requestedExecutionLevelElement.Attributes.Append(levelAttribute); if (executionUIAccessString != null) { XmlAttribute uiAccessAttribute = document.CreateAttribute("uiAccess"); uiAccessAttribute.Value = executionUIAccessString; requestedExecutionLevelElement.Attributes.Append(uiAccessAttribute); } } return(requestedPrivilegeElement); }
private void ConnectionString_Load(object sender, EventArgs e) { txtPassWord.PasswordChar = '*'; setcolor(); //string s = System.Reflection.Assembly.GetEntryAssembly().Location; string appPath = Application.StartupPath; PATH = appPath + @"\setting.xml"; doc = new XmlDocument(); //If there is no current file, then create a new one if (!System.IO.File.Exists(PATH)) { //Create neccessary nodes XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "UTF-8", "yes"); XmlComment comment = doc.CreateComment("This is an XML Generated File"); XmlElement root = doc.CreateElement("servers"); XmlElement server = doc.CreateElement("server"); // XmlAttribute sql = doc.CreateAttribute("sql"); XmlElement svr_name = doc.CreateElement("svr_name"); XmlElement db_name = doc.CreateElement("db_name"); XmlElement db_login = doc.CreateElement("db_login"); XmlElement db_passWord = doc.CreateElement("db_passWord"); //Add the values for each nodes // sql.Value = textBox1.Text; svr_name.InnerText = txtSRVName.Text; db_name.InnerText = txtDBName.Text; db_login.InnerText = txtLogin.Text; db_passWord.InnerText = Encrypt(txtPassWord.Text, "9ge340"); //Construct the document doc.AppendChild(declaration); doc.AppendChild(comment); doc.AppendChild(root); root.AppendChild(server); // server.Attributes.Append(sql); server.AppendChild(svr_name); server.AppendChild(db_name); server.AppendChild(db_login); server.AppendChild(db_passWord); doc.Save(PATH); } else { doc = new XmlDocument(); doc.Load(PATH); XmlElement root = doc.DocumentElement; XmlElement server = doc.CreateElement("server"); XmlElement currentPosition; //Get root element server = doc.DocumentElement; //Determine maximum possible index int max = server.GetElementsByTagName("server").Count - 1; //Get the record at the current index currentPosition = (XmlElement)root.ChildNodes[max]; if (currentPosition != null) { txtSRVName.Text = currentPosition.ChildNodes[0].InnerText; txtDBName.Text = currentPosition.GetElementsByTagName("db_name")[0].InnerText; txtLogin.Text = currentPosition.ChildNodes[2].InnerText; txtPassWord.Text = Decrypt(currentPosition.ChildNodes[3].InnerText, "9ge340"); } try { using (SqlConnection con = new SqlConnection(da.GetConnectionString())) { SqlCommand command = new SqlCommand(); con.Open(); con.Close(); // this.Hide(); //Form1 Form1 = new Form1();// نمایش فرم تنظیمات //Form1.Show(); //var msg = " اتصال به بانک با موفقیت انجام شد. "; //MessageForm.Show(msg, "اتصال به بانک", MessageFormIcons.Info, MessageFormButtons.Ok, color); connected = true; this.Close(); } } catch { var msg = "اطلاعات اتصال به بانک صحیح نمی باشد. "; MessageForm.Show(msg, "خطا در اتصال به بانک", MessageFormIcons.Warning, MessageFormButtons.Ok, color); //this.Close(); } } }
/// <summary> /// Сохранить настройки приложения в файле /// </summary> public bool Save(string fileName, out string errMsg) { try { XmlDocument xmlDoc = new XmlDocument(); XmlDeclaration xmlDecl = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null); xmlDoc.AppendChild(xmlDecl); XmlElement rootElem = xmlDoc.CreateElement("ScadaCommSvcConfig"); xmlDoc.AppendChild(rootElem); // Общие параметры rootElem.AppendChild(xmlDoc.CreateComment( Localization.UseRussian ? "Общие параметры" : "Common Parameters")); XmlElement paramsElem = xmlDoc.CreateElement("CommonParams"); rootElem.AppendChild(paramsElem); paramsElem.AppendParamElem("ServerUse", Params.ServerUse, "Использовать SCADA-Сервер", "Use SCADA-Server"); paramsElem.AppendParamElem("ServerHost", Params.ServerHost, "Имя компьютера или IP-адрес SCADA-Сервера", "SCADA-Server host or IP address"); paramsElem.AppendParamElem("ServerPort", Params.ServerPort, "Номер TCP-порта SCADA-Сервера", "SCADA-Server TCP port number"); paramsElem.AppendParamElem("ServerUser", Params.ServerUser, "Имя пользователя для подключения к SCADA-Серверу", "User name for the connection to SCADA-Server"); paramsElem.AppendParamElem("ServerPwd", Params.ServerPwd, "Пароль пользователя для подключения к SCADA-Серверу", "User password for the connection to SCADA-Server"); paramsElem.AppendParamElem("ServerTimeout", Params.ServerTimeout, "Таймаут ожидания ответа SCADA-Сервера, мс", "SCADA-Server response timeout, ms"); paramsElem.AppendParamElem("WaitForStop", Params.WaitForStop, "Ожидание остановки линий связи, мс", "Waiting for the communication lines temrination, ms"); paramsElem.AppendParamElem("SendAllDataPer", Params.SendAllDataPer, "Период передачи всех данных КП, с", "Sending all device data period, sec"); // Линии связи rootElem.AppendChild(xmlDoc.CreateComment( Localization.UseRussian ? "Линии связи" : "Communication Lines")); XmlElement linesElem = xmlDoc.CreateElement("CommLines"); rootElem.AppendChild(linesElem); foreach (CommLine commLine in CommLines) { linesElem.AppendChild(xmlDoc.CreateComment( (Localization.UseRussian ? "Линия " : "Line ") + commLine.Number)); XmlElement lineElem = xmlDoc.CreateElement("CommLine"); lineElem.SetAttribute("active", commLine.Active); lineElem.SetAttribute("bind", commLine.Bind); lineElem.SetAttribute("number", commLine.Number); lineElem.SetAttribute("name", commLine.Name); linesElem.AppendChild(lineElem); // канал связи XmlElement commChannelElem = xmlDoc.CreateElement("CommChannel"); lineElem.AppendChild(commChannelElem); commChannelElem.SetAttribute("type", commLine.CommCnlType); foreach (KeyValuePair <string, string> commCnlParam in commLine.CommCnlParams) { commChannelElem.AppendParamElem(commCnlParam.Key, commCnlParam.Value); } // параметры связи paramsElem = xmlDoc.CreateElement("LineParams"); lineElem.AppendChild(paramsElem); paramsElem.AppendParamElem("ReqTriesCnt", commLine.ReqTriesCnt, "Количество попыток перезапроса КП при ошибке", "Device request retries count on error"); paramsElem.AppendParamElem("CycleDelay", commLine.CycleDelay, "Задержка после цикла опроса, мс", "Delay after request cycle, ms"); paramsElem.AppendParamElem("CmdEnabled", commLine.CmdEnabled, "Команды ТУ разрешены", "Commands enabled"); paramsElem.AppendParamElem("ReqAfterCmd", commLine.ReqAfterCmd, "Опрос КП после команды ТУ", "Request device after command"); paramsElem.AppendParamElem("DetailedLog", commLine.DetailedLog, "Записывать в журнал подробную информацию", "Write detailed information to the log"); // пользовательские параметры paramsElem = xmlDoc.CreateElement("CustomParams"); lineElem.AppendChild(paramsElem); foreach (KeyValuePair <string, string> customParam in commLine.CustomParams) { paramsElem.AppendParamElem(customParam.Key, customParam.Value); } // последовательность опроса XmlElement reqSeqElem = xmlDoc.CreateElement("ReqSequence"); lineElem.AppendChild(reqSeqElem); foreach (KP kp in commLine.ReqSequence) { XmlElement kpElem = xmlDoc.CreateElement("KP"); kpElem.SetAttribute("active", kp.Active); kpElem.SetAttribute("bind", kp.Bind); kpElem.SetAttribute("number", kp.Number); kpElem.SetAttribute("name", kp.Name); kpElem.SetAttribute("dll", kp.Dll); kpElem.SetAttribute("address", kp.Address); kpElem.SetAttribute("callNum", kp.CallNum); kpElem.SetAttribute("timeout", kp.Timeout); kpElem.SetAttribute("delay", kp.Delay); kpElem.SetAttribute("time", kp.Time.ToString("T", DateTimeFormatInfo.InvariantInfo)); kpElem.SetAttribute("period", kp.Period); kpElem.SetAttribute("cmdLine", kp.CmdLine); reqSeqElem.AppendChild(kpElem); } } // сохранение XML-документа в файле if (CreateBakFile) { string bakName = fileName + ".bak"; File.Copy(fileName, bakName, true); } xmlDoc.Save(fileName); errMsg = ""; return(true); } catch (Exception ex) { errMsg = CommonPhrases.SaveAppSettingsError + ":" + Environment.NewLine + ex.Message; return(false); } }
XmlDocument SaveAsXml() { XmlDocument dom = new XmlDocument(); dom.AppendChild(dom.CreateXmlDeclaration("1.0", "utf-8", null)); XmlElement root = dom.CreateElement("document"); root.SetAttribute("type", "BLUMIND"); root.SetAttribute("editor_version", ProductInfo.Version); root.SetAttribute("document_version", Document.DocumentVersion.ToString()); dom.AppendChild(root); // XmlComment comment = dom.CreateComment("Create by Blumind, you can download it free from http://www.blumind.org"); root.AppendChild(comment); // information XmlElement infos = dom.CreateElement("information"); ST.WriteTextNode(infos, "author", Author); ST.WriteTextNode(infos, "company", Company); ST.WriteTextNode(infos, "version", Version); ST.WriteTextNode(infos, "description", Description); root.AppendChild(infos); // attributes XmlElement attrs = dom.CreateElement("attributes"); foreach (KeyValuePair <string, object> attr in Attributes) { XmlElement attr_e = dom.CreateElement("item"); attr_e.SetAttribute("name", attr.Key); if (attr.Value != null) { attr_e.InnerText = attr.Value.ToString(); } attrs.AppendChild(attr_e); } root.AppendChild(attrs); // charts XmlElement charts = dom.CreateElement("charts"); charts.SetAttribute("active_chart", ActiveChartIndex.ToString()); foreach (ChartPage cdoc in Charts) { var chart_e = dom.CreateElement("chart"); cdoc.Serialize(dom, chart_e); //switch (cdoc.Type) //{ // case ChartType.MindMap: // MindMapIO.SaveAsXml((MindMap)cdoc, chart_e); // break; // default: // continue; //} charts.AppendChild(chart_e); } root.AppendChild(charts); return(dom); }
public static void CommentChildNodeCount() { var xmlDocument = new XmlDocument(); var item = xmlDocument.CreateComment("comment"); var clonedTrue = item.CloneNode(true); var clonedFalse = item.CloneNode(false); Assert.Equal(0, item.ChildNodes.Count); Assert.Equal(0, clonedTrue.ChildNodes.Count); Assert.Equal(0, clonedFalse.ChildNodes.Count); }
private static bool WriteToXML(List <MedicalCourse> courses) { //путь string path = @"courses.xml"; //создание главного объекта документа XmlDocument XmlDoc = new XmlDocument(); /*<?xml version="1.0" encoding="utf-8" ?> */ //создание объявления (декларации) документа XmlDeclaration XmlDec = XmlDoc.CreateXmlDeclaration("1.0", "utf-8", null); //добавляем в документ XmlDoc.AppendChild(XmlDec); /*<!--база данных-->*/ //комментарий уровня root XmlComment Comment0 = XmlDoc.CreateComment("Certification Center database"); //добавляем в документ XmlDoc.AppendChild(Comment0); /*<database name="abc"></database>*/ //создание корневого элемента XmlElement ElementDatabase = XmlDoc.CreateElement("database"); //создание атрибута ElementDatabase.SetAttribute("name", "certification-center"); //добавляем в документ XmlDoc.AppendChild(ElementDatabase); /*<!--описание структуры таблицы-->*/ //комментарий уровня вложенности root/child XmlComment Comment1 = XmlDoc.CreateComment("Описание структуры таблицы"); //добавляем в ElementDatabase ElementDatabase.AppendChild(Comment1); /*<table_structure name="courses"></table_structure>*/ //создание дочернего элемента уровня вложенности root/child XmlElement ElementTable_Structure = XmlDoc.CreateElement("table_structure"); //создание атрибута ElementTable_Structure.SetAttribute("name", "courses"); //добавляем в ElementDatabase ElementDatabase.AppendChild(ElementTable_Structure); /*<field Field="course_id" type="int"></field>*/ //создание дочернего элемента уровня вложенности root/child/child XmlElement ElementField0 = XmlDoc.CreateElement("field"); //создание атрибута ElementField0.SetAttribute("Field", "course_id"); ElementField0.SetAttribute("type", "int"); //добавляем в ElementTable_Structure ElementTable_Structure.AppendChild(ElementField0); /*<field Field="course_name" type="string"></field>*/ //создание дочернего элемента уровня вложенности root/child/child XmlElement ElementField1 = XmlDoc.CreateElement("field"); //создание атрибута ElementField1.SetAttribute("Field", "course_name"); ElementField1.SetAttribute("type", "string"); //добавляем в ElementTable_Structure ElementTable_Structure.AppendChild(ElementField1); /*<field Field="qualification" type="int"></field>*/ //создание дочернего элемента уровня вложенности root/child/child XmlElement ElementField2 = XmlDoc.CreateElement("field"); //создание атрибута ElementField2.SetAttribute("Field", "qualification"); ElementField2.SetAttribute("type", "int"); //добавляем в ElementTable_Structure ElementTable_Structure.AppendChild(ElementField2); /*<!--данные таблицы-->*/ //комментарий уровня вложенности root/child XmlComment Comment2 = XmlDoc.CreateComment("Данные таблицы"); //добавляем в ElementDatabase ElementDatabase.AppendChild(Comment2); /*<table_data name="courses"></table_data>*/ //создание дочернего элемента уровня вложенности root/child XmlElement ElementTable_Data = XmlDoc.CreateElement("table_data"); //создание атрибута ElementTable_Data.SetAttribute("name", "courses"); //добавляем в ElementDatabase ElementDatabase.AppendChild(ElementTable_Data); for (int i = 0; i < courses.Count; i++) { /*<row><row>*/ //создание дочернего элемента уровня вложенности root/child/child XmlElement ElementRow = XmlDoc.CreateElement("row"); //добавляем в ElementTable_Data ElementTable_Data.AppendChild(ElementRow); /*<field name="course_id"></field>*/ //создание дочернего элемента уровня вложенности root/child/child/child XmlElement ElementFieldId = XmlDoc.CreateElement("field"); //создание атрибута ElementFieldId.SetAttribute("name", "course_id"); //создание контента ElementFieldId.InnerText = courses[i].Id.ToString(); //добавляем в ElementRow ElementRow.AppendChild(ElementFieldId); /*<field name="course_name"></field>*/ //создание дочернего элемента уровня вложенности root/child/child/child XmlElement ElementFieldName = XmlDoc.CreateElement("field"); //создание атрибута ElementFieldName.SetAttribute("name", "course_name"); //создание контента ElementFieldName.InnerText = courses[i].Name; //добавляем в ElementRow ElementRow.AppendChild(ElementFieldName); /*<field name="qualification"></field>*/ //создание дочернего элемента уровня вложенности root/child/child/child XmlElement ElementFieldAmount = XmlDoc.CreateElement("field"); //создание атрибута ElementFieldAmount.SetAttribute("name", "qualification"); //создание контента ElementFieldAmount.InnerText = courses[i].Qualification.ToString(); //добавляем в ElementRow ElementRow.AppendChild(ElementFieldAmount); } XmlDoc.Save(path); return(true); }
public static void CheckNoChildrenOnComment() { var xmlDocument = new XmlDocument(); Assert.False(xmlDocument.CreateComment("info").HasChildNodes); }
public static void AppendNullToCommentNodeTest() { var xmlDocument = new XmlDocument(); AppendNullToXmlCharacterData(xmlDocument.CreateComment("a")); }
public override void Comment(string content) { currentElement.AppendChild(xmldoc.CreateComment(content)); }
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); }
/// <param name="xmlDoc"></param> /// <param name="rootNode"></param> private void CreateConsumptionNodeComment(XmlDocument xmlDoc, XmlNode rootNode) { XmlComment comment = xmlDoc.CreateComment("Consumption values are per household, or per production unit"); rootNode.AppendChild(comment); }
private void MigrateFile(string path) { try { File.Copy(path, path + ".bak", true); } catch {} string removedContent = ""; XmlDocument csprojfile = new XmlDocument(); csprojfile.Load(path); XmlNamespaceManager newnsmgr = new XmlNamespaceManager(csprojfile.NameTable); newnsmgr.AddNamespace("ns", "http://schemas.microsoft.com/developer/msbuild/2003"); XmlNode nodeProject = csprojfile.SelectSingleNode("/ns:Project", newnsmgr); //check for nodeimport CheckImportNode(csprojfile, nodeProject, @"$(SolutionDir)\SPSF.targets", @"!Exists('$(MSBuildProjectDirectory)\..\SPSF.targets')"); CheckImportNode(csprojfile, nodeProject, @"$(MSBuildProjectDirectory)\..\SPSF.targets", @"Exists('$(MSBuildProjectDirectory)\..\SPSF.targets')"); RemoveImportNode(csprojfile, nodeProject, @"$(SolutionDir)\SharePointTargets.targets"); RemoveImportNode(csprojfile, nodeProject, @"$(MSBuildProjectDirectory)\..\SharePointTargets.targets"); /* * <Import Condition="!Exists('$(MSBuildProjectDirectory)\..\SPSF.targets')" Project="$(SolutionDir)\SPSF.targets" /> * <Import Condition=" Exists('$(MSBuildProjectDirectory)\..\SPSF.targets')" Project="$(MSBuildProjectDirectory)\..\SPSF.targets" /> * */ XmlNode nodeBeforeBuild = csprojfile.SelectSingleNode("/ns:Project/ns:Target[@Name='BeforeBuild' and @DependsOnTargets='$(BeforeBuildDependsOn)']", newnsmgr); if (nodeBeforeBuild == null) { XmlNode nodeBeforeBuildOther = csprojfile.SelectSingleNode("/ns:Project/ns:Target[@Name='BeforeBuild']", newnsmgr); if (nodeBeforeBuildOther != null) { //remove this node with same name removedContent += nodeBeforeBuildOther.OuterXml + Environment.NewLine; nodeProject.RemoveChild(nodeBeforeBuildOther); } AddBeforeBuildNode(csprojfile, nodeProject); } XmlNode nodeAfterBuild = csprojfile.SelectSingleNode("/ns:Project/ns:Target[@Name='AfterBuild' and @DependsOnTargets='$(AfterBuildDependsOn)']", newnsmgr); if (nodeAfterBuild == null) { XmlNode nodeAfterBuildOther = csprojfile.SelectSingleNode("/ns:Project/ns:Target[@Name='AfterBuild']", newnsmgr); if (nodeAfterBuildOther != null) { //remove this node with same name removedContent += nodeAfterBuildOther.OuterXml + Environment.NewLine; nodeProject.RemoveChild(nodeAfterBuildOther); } AddAfterBuildNode(csprojfile, nodeProject); } if (removedContent != "") { XmlComment comment = csprojfile.CreateComment("Following content has been removed during migration with SPSF" + Environment.NewLine + removedContent); nodeProject.AppendChild(comment); } csprojfile.Save(path); }
/// <param name="xmlDoc"></param> /// <param name="rootNode"></param> private void CreateVisitNodeComment(XmlDocument xmlDoc, XmlNode rootNode) { XmlComment comment = xmlDoc.CreateComment("Visitor Values are multiplies of 100th of a person per cell."); rootNode.AppendChild(comment); }
/// <summary> /// Creates a comment node containing the specified data. /// </summary> /// <param name="data">The comment data.</param> /// <returns>A new <see cref="DOMComment"/>.</returns> public virtual DOMComment createComment(string data) { XmlComment comment = XmlDocument.CreateComment(data); return(new DOMComment(comment)); }
} // end readXML /// <param name="fullPathFileName"></param> /// <returns></returns> public override bool writeXML(string fullPathFileName) { XmlDocument xmlDoc = new XmlDocument(); XmlNode rootNode = xmlDoc.CreateElement("WG_CityMod"); XmlAttribute attribute = xmlDoc.CreateAttribute("version"); attribute.Value = "6"; rootNode.Attributes.Append(attribute); /* * attribute = xmlDoc.CreateAttribute("experimental"); * attribute.Value = DataStore.enableExperimental ? "true" : "false"; * rootNode.Attributes.Append(attribute); */ xmlDoc.AppendChild(rootNode); XmlNode popNode = xmlDoc.CreateElement(popNodeName); attribute = xmlDoc.CreateAttribute("strictCapacity"); attribute.Value = DataStore.strictCapacity ? "true" : "false"; popNode.Attributes.Append(attribute); XmlNode consumeNode = xmlDoc.CreateElement(consumeNodeName); XmlNode visitNode = xmlDoc.CreateElement(visitNodeName); XmlNode pollutionNode = xmlDoc.CreateElement(pollutionNodeName); XmlNode productionNode = xmlDoc.CreateElement(productionNodeName); try { MakeNodes(xmlDoc, "ResidentialLow", DataStore.residentialLow, popNode, consumeNode, visitNode, pollutionNode, productionNode); MakeNodes(xmlDoc, "ResidentialHigh", DataStore.residentialHigh, popNode, consumeNode, visitNode, pollutionNode, productionNode); MakeNodes(xmlDoc, "ResEcoLow", DataStore.resEcoLow, popNode, consumeNode, visitNode, pollutionNode, productionNode); MakeNodes(xmlDoc, "ResEcoHigh", DataStore.resEcoHigh, popNode, consumeNode, visitNode, pollutionNode, productionNode); MakeNodes(xmlDoc, "CommercialLow", DataStore.commercialLow, popNode, consumeNode, visitNode, pollutionNode, productionNode); MakeNodes(xmlDoc, "CommercialHigh", DataStore.commercialHigh, popNode, consumeNode, visitNode, pollutionNode, productionNode); MakeNodes(xmlDoc, "CommercialEco", DataStore.commercialEco, popNode, consumeNode, visitNode, pollutionNode, productionNode); MakeNodes(xmlDoc, "CommercialTourist", DataStore.commercialTourist, popNode, consumeNode, visitNode, pollutionNode, productionNode); MakeNodes(xmlDoc, "CommercialLeisure", DataStore.commercialLeisure, popNode, consumeNode, visitNode, pollutionNode, productionNode); MakeNodes(xmlDoc, "Office", DataStore.office, popNode, consumeNode, visitNode, pollutionNode, productionNode); MakeNodes(xmlDoc, "OfficeHighTech", DataStore.officeHighTech, popNode, consumeNode, visitNode, pollutionNode, productionNode); MakeNodes(xmlDoc, "Industry", DataStore.industry, popNode, consumeNode, visitNode, pollutionNode, productionNode); MakeNodes(xmlDoc, "IndustryFarm", DataStore.industry_farm, popNode, consumeNode, visitNode, pollutionNode, productionNode); MakeNodes(xmlDoc, "IndustryForest", DataStore.industry_forest, popNode, consumeNode, visitNode, pollutionNode, productionNode); MakeNodes(xmlDoc, "IndustryOre", DataStore.industry_ore, popNode, consumeNode, visitNode, pollutionNode, productionNode); MakeNodes(xmlDoc, "IndustryOil", DataStore.industry_oil, popNode, consumeNode, visitNode, pollutionNode, productionNode); } catch (Exception e) { Debugging.panelMessage(e.Message); } // First segment CreatePopulationNodeComment(xmlDoc, rootNode); rootNode.AppendChild(popNode); CreateConsumptionNodeComment(xmlDoc, rootNode); rootNode.AppendChild(consumeNode); CreateVisitNodeComment(xmlDoc, rootNode); rootNode.AppendChild(visitNode); CreateProductionNodeComment(xmlDoc, rootNode); rootNode.AppendChild(productionNode); CreatePollutionNodeComment(xmlDoc, rootNode); rootNode.AppendChild(pollutionNode); // Add mesh names to XML for house holds XmlComment comment = xmlDoc.CreateComment(" ******* House hold data ******* "); rootNode.AppendChild(comment); XmlNode overrideHouseholdNode = xmlDoc.CreateElement(overrideHouseName); attribute = xmlDoc.CreateAttribute("printResNames"); attribute.Value = DataStore.printResidentialNames ? "true" : "false"; overrideHouseholdNode.Attributes.Append(attribute); attribute = xmlDoc.CreateAttribute("mergeResNames"); attribute.Value = DataStore.mergeResidentialNames ? "true" : "false"; overrideHouseholdNode.Attributes.Append(attribute); SortedList <string, int> list = new SortedList <string, int>(DataStore.householdCache); foreach (string name in list.Keys) { XmlNode meshNameNode = xmlDoc.CreateElement(meshName); meshNameNode.InnerXml = name; attribute = xmlDoc.CreateAttribute("value"); int value = 1; DataStore.householdCache.TryGetValue(name, out value); attribute.Value = Convert.ToString(value); meshNameNode.Attributes.Append(attribute); overrideHouseholdNode.AppendChild(meshNameNode); } rootNode.AppendChild(overrideHouseholdNode); // Append the overrideHousehold to root // Add mesh names to XML comment = xmlDoc.CreateComment(" ******* Printed out house hold data. To activate the value, move the line into the override segment ******* "); rootNode.AppendChild(comment); XmlNode printHouseholdNode = xmlDoc.CreateElement(printHouseName); list = new SortedList <string, int>(DataStore.housePrintOutCache); foreach (string data in list.Keys) { XmlNode meshNameNode = xmlDoc.CreateElement(meshName); meshNameNode.InnerXml = data; attribute = xmlDoc.CreateAttribute("value"); int value = 1; DataStore.housePrintOutCache.TryGetValue(data, out value); attribute.Value = Convert.ToString(value); meshNameNode.Attributes.Append(attribute); printHouseholdNode.AppendChild(meshNameNode); } rootNode.AppendChild(printHouseholdNode); // Append the printHousehold to root // Add mesh names to XML list = new SortedList <string, int>(DataStore.bonusHouseholdCache); if (list.Keys.Count != 0) { XmlNode bonusHouseholdNode = xmlDoc.CreateElement(bonusHouseName); foreach (string data in list.Keys) { XmlNode meshNameNode = xmlDoc.CreateElement(meshName); meshNameNode.InnerXml = data; attribute = xmlDoc.CreateAttribute("value"); DataStore.bonusHouseholdCache.TryGetValue(data, out int value); attribute.Value = Convert.ToString(value); meshNameNode.Attributes.Append(attribute); bonusHouseholdNode.AppendChild(meshNameNode); } rootNode.AppendChild(bonusHouseholdNode); // Append the bonusHousehold to root } // Add mesh names to XML for workers comment = xmlDoc.CreateComment(" ******* Worker data ******* "); rootNode.AppendChild(comment); XmlNode overrideWorkNode = xmlDoc.CreateElement(overrideWorkName); attribute = xmlDoc.CreateAttribute("printWorkNames"); attribute.Value = DataStore.printEmploymentNames ? "true" : "false"; overrideWorkNode.Attributes.Append(attribute); attribute = xmlDoc.CreateAttribute("mergeWorkNames"); attribute.Value = DataStore.mergeEmploymentNames ? "true" : "false"; overrideWorkNode.Attributes.Append(attribute); SortedList <string, int> wList = new SortedList <string, int>(DataStore.workerCache); foreach (string name in wList.Keys) { XmlNode meshNameNode = xmlDoc.CreateElement(meshName); meshNameNode.InnerXml = name; int value = 1; DataStore.workerCache.TryGetValue(name, out value); attribute = xmlDoc.CreateAttribute("value"); attribute.Value = Convert.ToString(value); meshNameNode.Attributes.Append(attribute); overrideWorkNode.AppendChild(meshNameNode); } rootNode.AppendChild(overrideWorkNode); // Append the overrideWorkers to root // Add mesh names to dictionary comment = xmlDoc.CreateComment(" ******* Printed out worker data. To activate the value, move the line into the override segment ******* "); rootNode.AppendChild(comment); XmlNode printWorkNode = xmlDoc.CreateElement(printWorkName); wList = new SortedList <string, int>(DataStore.workerPrintOutCache); foreach (string data in wList.Keys) { if (!DataStore.workerCache.ContainsKey(data)) { XmlNode meshNameNode = xmlDoc.CreateElement(meshName); meshNameNode.InnerXml = data; DataStore.workerPrintOutCache.TryGetValue(data, out int value); attribute = xmlDoc.CreateAttribute("value"); attribute.Value = Convert.ToString(value); meshNameNode.Attributes.Append(attribute); printWorkNode.AppendChild(meshNameNode); } } rootNode.AppendChild(printWorkNode); // Append the printWorkers to root // Add mesh names to dictionary wList = new SortedList <string, int>(DataStore.bonusWorkerCache); if (wList.Keys.Count != 0) { XmlNode bonusWorkNode = xmlDoc.CreateElement(bonusWorkName); foreach (string data in wList.Keys) { XmlNode meshNameNode = xmlDoc.CreateElement(meshName); meshNameNode.InnerXml = data; DataStore.bonusWorkerCache.TryGetValue(data, out int value); attribute = xmlDoc.CreateAttribute("value"); attribute.Value = Convert.ToString(value); meshNameNode.Attributes.Append(attribute); bonusWorkNode.AppendChild(meshNameNode); } rootNode.AppendChild(bonusWorkNode); // Append the bonusWorkers to root } try { if (File.Exists(fullPathFileName)) { if (File.Exists(fullPathFileName + ".bak")) { File.Delete(fullPathFileName + ".bak"); } File.Move(fullPathFileName, fullPathFileName + ".bak"); } } catch (Exception e) { Debugging.panelMessage(e.Message); } try { xmlDoc.Save(fullPathFileName); } catch (Exception e) { Debugging.panelMessage(e.Message); return(false); // Only time when we say there's an error } return(true); } // end writeXML
public static void SaveProfile() { if (Options.ProfileName is null) { Logger.Warning("SaveProfile - ProfileName is null!"); return; } string fileName = Path.Combine(Options.AppDataPath, Options.ProfileName); Logger.Information("SaveProfile - start {filename}", fileName); XmlDocument dom = new XmlDocument(); XmlDeclaration decl = dom.CreateXmlDeclaration("1.0", "utf-8", null); dom.AppendChild(decl); XmlElement sr = dom.CreateElement("Options"); XmlComment comment = dom.CreateComment("Output Path"); sr.AppendChild(comment); XmlElement elem = dom.CreateElement("OutputPath"); elem.SetAttribute("path", Options.OutputPath); sr.AppendChild(elem); comment = dom.CreateComment("ItemSize controls the size of images in items tab"); sr.AppendChild(comment); elem = dom.CreateElement("ItemSize"); elem.SetAttribute("width", Options.ArtItemSizeWidth.ToString()); elem.SetAttribute("height", Options.ArtItemSizeHeight.ToString()); sr.AppendChild(elem); comment = dom.CreateComment("ItemClip images in items tab shrinked or clipped"); sr.AppendChild(comment); elem = dom.CreateElement("ItemClip"); elem.SetAttribute("active", Options.ArtItemClip.ToString()); sr.AppendChild(elem); comment = dom.CreateComment("CacheData should mul entries be cached for faster load"); sr.AppendChild(comment); elem = dom.CreateElement("CacheData"); elem.SetAttribute("active", Files.CacheData.ToString()); sr.AppendChild(elem); comment = dom.CreateComment("NewMapSize Felucca/Trammel width 7168?"); sr.AppendChild(comment); elem = dom.CreateElement("NewMapSize"); elem.SetAttribute("active", Map.Felucca.Width == 7168 ? true.ToString() : false.ToString()); sr.AppendChild(elem); comment = dom.CreateComment("UseMapDiff should mapdiff files be used"); sr.AppendChild(comment); elem = dom.CreateElement("UseMapDiff"); elem.SetAttribute("active", Map.UseDiff.ToString()); sr.AppendChild(elem); comment = dom.CreateComment("Alternative layout in item/landtile/texture tab?"); sr.AppendChild(comment); elem = dom.CreateElement("AlternativeDesign"); elem.SetAttribute("active", Options.DesignAlternative.ToString()); sr.AppendChild(elem); comment = dom.CreateComment("Make the right panel into the sounds tab visible"); sr.AppendChild(comment); elem = dom.CreateElement("RightPanelInSoundsTab"); elem.SetAttribute("active", Options.RightPanelInSoundsTab.ToString()); sr.AppendChild(elem); comment = dom.CreateComment("Use Hashfile to speed up load?"); sr.AppendChild(comment); elem = dom.CreateElement("UseHashFile"); elem.SetAttribute("active", Files.UseHashFile.ToString()); sr.AppendChild(elem); comment = dom.CreateComment("Should an Update Check be done on startup?"); sr.AppendChild(comment); elem = dom.CreateElement("UpdateCheck"); elem.SetAttribute("active", UpdateCheckOnStart.ToString()); sr.AppendChild(elem); comment = dom.CreateComment("Defines the cmd to send Client to loc"); sr.AppendChild(comment); comment = dom.CreateComment("{1} = x, {2} = y, {3} = z, {4} = mapid, {5} = mapname"); sr.AppendChild(comment); elem = dom.CreateElement("SendCharToLoc"); elem.SetAttribute("cmd", Options.MapCmd); elem.SetAttribute("args", Options.MapArgs); sr.AppendChild(elem); comment = dom.CreateComment("Defines the map names"); sr.AppendChild(comment); elem = dom.CreateElement("MapNames"); elem.SetAttribute("map0", Options.MapNames[0]); elem.SetAttribute("map1", Options.MapNames[1]); elem.SetAttribute("map2", Options.MapNames[2]); elem.SetAttribute("map3", Options.MapNames[3]); elem.SetAttribute("map4", Options.MapNames[4]); elem.SetAttribute("map5", Options.MapNames[5]); sr.AppendChild(elem); comment = dom.CreateComment("Extern Tools settings"); sr.AppendChild(comment); if (ExternTools != null) { foreach (ExternTool tool in ExternTools) { XmlElement externalToolElement = dom.CreateElement("ExternTool"); externalToolElement.SetAttribute("name", tool.Name); externalToolElement.SetAttribute("path", tool.FileName); for (int i = 0; i < tool.Args.Count; i++) { XmlElement argsElement = dom.CreateElement("Args"); argsElement.SetAttribute("name", tool.ArgsName[i]); argsElement.SetAttribute("arg", tool.Args[i]); externalToolElement.AppendChild(argsElement); } sr.AppendChild(externalToolElement); } } comment = dom.CreateComment("Loaded Plugins"); sr.AppendChild(comment); if (Options.PluginsToLoad != null) { foreach (string plugIn in Options.PluginsToLoad) { Logger.Information("SaveProfile - saving plugin {plugIn}", plugIn); XmlElement xmlPlugin = dom.CreateElement("Plugin"); xmlPlugin.SetAttribute("name", plugIn); sr.AppendChild(xmlPlugin); } } comment = dom.CreateComment("Path settings"); sr.AppendChild(comment); elem = dom.CreateElement("RootPath"); elem.SetAttribute("path", Files.RootDir); sr.AppendChild(elem); List <string> sorter = new List <string>(Files.MulPath.Keys); sorter.Sort(); foreach (string key in sorter) { XmlElement path = dom.CreateElement("Paths"); path.SetAttribute("key", key); path.SetAttribute("value", Files.MulPath[key]); sr.AppendChild(path); } dom.AppendChild(sr); comment = dom.CreateComment("Disabled Tab Views"); sr.AppendChild(comment); foreach (KeyValuePair <int, bool> kvp in Options.ChangedViewState) { if (kvp.Value) { continue; } XmlElement viewState = dom.CreateElement("TabView"); viewState.SetAttribute("tab", kvp.Key.ToString()); sr.AppendChild(viewState); } comment = dom.CreateComment("ViewState of the MainForm"); sr.AppendChild(comment); elem = dom.CreateElement("ViewState"); elem.SetAttribute("Active", StoreFormState.ToString()); elem.SetAttribute("Maximised", MaximisedForm.ToString()); elem.SetAttribute("PositionX", FormPosition.X.ToString()); elem.SetAttribute("PositionY", FormPosition.Y.ToString()); elem.SetAttribute("Height", FormSize.Height.ToString()); elem.SetAttribute("Width", FormSize.Width.ToString()); sr.AppendChild(elem); comment = dom.CreateComment("TileData Options"); sr.AppendChild(comment); elem = dom.CreateElement("TileDataDirectlySaveOnChange"); elem.SetAttribute("value", Options.TileDataDirectlySaveOnChange.ToString()); sr.AppendChild(elem); dom.Save(fileName); Logger.Information("SaveProfile - done {filename}", fileName); }
public static void InsertCommentNodeToDocumentFragment() { var xmlDocument = new XmlDocument(); var documentFragment = xmlDocument.CreateDocumentFragment(); var node = xmlDocument.CreateComment("some comment"); Assert.Equal(0, documentFragment.ChildNodes.Count); var result = documentFragment.InsertBefore(node, null); Assert.Same(node, result); Assert.Equal(1, documentFragment.ChildNodes.Count); }
/// <summary> /// Get XmlNode containing the node. /// </summary> /// <param name="xDoc">XmlDocument object used to spawn node</param> /// <param name="full">If true, all possible attributes will be output. /// If false, only filled and appropriate attributes will be output.</param> public override XmlNode ToXml(XmlDocument xDoc, bool full = false) { XmlComment xCom = xDoc.CreateComment(Name); return(xCom); }
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); } } }
public static void FirstChildOfNewDocumentFragmentWithChildren() { var xmlDocument = new XmlDocument(); var fragment = xmlDocument.CreateDocumentFragment(); var node1 = xmlDocument.CreateComment("comment"); var node2 = xmlDocument.CreateCDataSection("some random text"); fragment.AppendChild(node1); fragment.AppendChild(node2); Assert.Same(node1, fragment.FirstChild); }
public static void NewlyCreatedComment() { var xmlDocument = new XmlDocument(); var node = xmlDocument.CreateComment("comment"); Assert.Null(node.NextSibling); }
public static bool ExportInputManager(RUISInputManager inputManager, string filename) { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", "yes"); XmlElement inputManagerRootElement = xmlDoc.CreateElement("ns2", "RUISInputManager", "http://ruisystem.net/RUISInputManager"); xmlDoc.AppendChild(inputManagerRootElement); XmlComment booleanComment = xmlDoc.CreateComment("Boolean values always with a lower case, e.g. \"true\" or \"false\""); inputManagerRootElement.AppendChild(booleanComment); XmlElement psMoveSettingsElement = xmlDoc.CreateElement("PSMoveSettings"); inputManagerRootElement.AppendChild(psMoveSettingsElement); XmlElement psMoveEnabledElement = xmlDoc.CreateElement("enabled"); psMoveEnabledElement.SetAttribute("value", inputManager.enablePSMove.ToString().ToLowerInvariant()); psMoveSettingsElement.AppendChild(psMoveEnabledElement); XmlElement psMoveIPElement = xmlDoc.CreateElement("ip"); psMoveIPElement.SetAttribute("value", inputManager.PSMoveIP.ToString()); psMoveSettingsElement.AppendChild(psMoveIPElement); XmlElement psMovePortElement = xmlDoc.CreateElement("port"); psMovePortElement.SetAttribute("value", inputManager.PSMovePort.ToString()); psMoveSettingsElement.AppendChild(psMovePortElement); XmlElement psMoveAutoConnectElement = xmlDoc.CreateElement("autoConnect"); psMoveAutoConnectElement.SetAttribute("value", inputManager.connectToPSMoveOnStartup.ToString().ToLowerInvariant()); psMoveSettingsElement.AppendChild(psMoveAutoConnectElement); XmlElement psMoveEnableInGameCalibration = xmlDoc.CreateElement("enableInGameCalibration"); psMoveEnableInGameCalibration.SetAttribute("value", inputManager.enableMoveCalibrationDuringPlay.ToString().ToLowerInvariant()); psMoveSettingsElement.AppendChild(psMoveEnableInGameCalibration); XmlElement psMoveMaxControllersElement = xmlDoc.CreateElement("maxControllers"); psMoveMaxControllersElement.SetAttribute("value", inputManager.amountOfPSMoveControllers.ToString()); psMoveSettingsElement.AppendChild(psMoveMaxControllersElement); XmlElement kinectSettingsElement = xmlDoc.CreateElement("KinectSettings"); inputManagerRootElement.AppendChild(kinectSettingsElement); XmlElement kinectEnabledElement = xmlDoc.CreateElement("enabled"); kinectEnabledElement.SetAttribute("value", inputManager.enableKinect.ToString().ToLowerInvariant()); kinectSettingsElement.AppendChild(kinectEnabledElement); XmlElement maxKinectPlayersElement = xmlDoc.CreateElement("maxPlayers"); maxKinectPlayersElement.SetAttribute("value", inputManager.maxNumberOfKinectPlayers.ToString()); kinectSettingsElement.AppendChild(maxKinectPlayersElement); XmlElement kinectFloorDetectionElement = xmlDoc.CreateElement("floorDetection"); kinectFloorDetectionElement.SetAttribute("value", inputManager.kinectFloorDetection.ToString().ToLowerInvariant()); kinectSettingsElement.AppendChild(kinectFloorDetectionElement); XmlElement jumpGestureElement = xmlDoc.CreateElement("jumpGestureEnabled"); jumpGestureElement.SetAttribute("value", inputManager.jumpGestureEnabled.ToString().ToLowerInvariant()); kinectSettingsElement.AppendChild(jumpGestureElement); XmlElement kinect2SettingsElement = xmlDoc.CreateElement("Kinect2Settings"); inputManagerRootElement.AppendChild(kinect2SettingsElement); XmlElement kinect2EnabledElement = xmlDoc.CreateElement("enabled"); kinect2EnabledElement.SetAttribute("value", inputManager.enableKinect2.ToString().ToLowerInvariant()); kinect2SettingsElement.AppendChild(kinect2EnabledElement); XmlElement kinect2FloorDetectionElement = xmlDoc.CreateElement("floorDetection"); kinect2FloorDetectionElement.SetAttribute("value", inputManager.kinect2FloorDetection.ToString().ToLowerInvariant()); kinect2SettingsElement.AppendChild(kinect2FloorDetectionElement); XmlElement razerSettingsElement = xmlDoc.CreateElement("RazerSettings"); inputManagerRootElement.AppendChild(razerSettingsElement); XmlElement razerEnabledElement = xmlDoc.CreateElement("enabled"); razerEnabledElement.SetAttribute("value", inputManager.enableRazerHydra.ToString().ToLowerInvariant()); razerSettingsElement.AppendChild(razerEnabledElement); XmlElement riftDriftSettingsElement = xmlDoc.CreateElement("OculusDriftSettings"); inputManagerRootElement.AppendChild(riftDriftSettingsElement); //XmlElement magnetometerDriftCorrectionElement = xmlDoc.CreateElement("magnetometerDriftCorrection"); //magnetometerDriftCorrectionElement.SetAttribute("value", System.Enum.GetName(typeof(RUISInputManager.RiftMagnetometer), inputManager.riftMagnetometerMode)); //riftDriftSettingsElement.AppendChild(magnetometerDriftCorrectionElement); XmlElement kinectDriftCorrectionElement = xmlDoc.CreateElement("kinectDriftCorrectionIfAvailable"); kinectDriftCorrectionElement.SetAttribute("value", inputManager.kinectDriftCorrectionPreferred.ToString().ToLowerInvariant()); riftDriftSettingsElement.AppendChild(kinectDriftCorrectionElement); XMLUtil.SaveXmlToFile(filename, xmlDoc); return true; }
private void BSave_Click(object sender, EventArgs e) { if (TBAura1.Text == "") { TBAura1.Text = "0"; } if (TBItem1.Text == "") { TBItem1.Text = "0"; } if (TBQuest11.Text == "") { TBQuest11.Text = "0"; } if (TBQuest12.Text == "") { TBQuest12.Text = "0"; } if (TBQuest13.Text == "") { TBQuest13.Text = "0"; } if (TBAura2.Text == "") { TBAura2.Text = "0"; } if (TBItem2.Text == "") { TBItem2.Text = "0"; } if (TBQuest21.Text == "") { TBQuest21.Text = "0"; } if (TBQuest22.Text == "") { TBQuest22.Text = "0"; } if (TBQuest23.Text == "") { TBQuest23.Text = "0"; } if (TBAura3.Text == "") { TBAura3.Text = "0"; } if (TBItem3.Text == "") { TBItem3.Text = "0"; } if (TBQuest31.Text == "") { TBQuest31.Text = "0"; } if (TBQuest32.Text == "") { TBQuest32.Text = "0"; } if (TBQuest33.Text == "") { TBQuest33.Text = "0"; } if (TBAura4.Text == "") { TBAura4.Text = "0"; } if (TBItem4.Text == "") { TBItem4.Text = "0"; } if (TBQuest41.Text == "") { TBQuest41.Text = "0"; } if (TBQuest42.Text == "") { TBQuest42.Text = "0"; } if (TBQuest43.Text == "") { TBQuest43.Text = "0"; } if (TBAura5.Text == "") { TBAura5.Text = "0"; } if (TBItem5.Text == "") { TBItem5.Text = "0"; } if (TBQuest51.Text == "") { TBQuest51.Text = "0"; } if (TBQuest52.Text == "") { TBQuest52.Text = "0"; } if (TBQuest53.Text == "") { TBQuest53.Text = "0"; } if (TBAura6.Text == "") { TBAura6.Text = "0"; } if (TBItem6.Text == "") { TBItem6.Text = "0"; } if (TBQuest61.Text == "") { TBQuest61.Text = "0"; } if (TBQuest62.Text == "") { TBQuest62.Text = "0"; } if (TBQuest63.Text == "") { TBQuest63.Text = "0"; } if (CB1.Checked && TBAura1.Text == "0") { Logging.Write("ItemForAura: Line 1: Please insert a Aura ID or Pluginpart wont work."); CB1.Checked = false; } if (CB2.Checked && TBAura2.Text == "0") { Logging.Write("ItemForAura: Line 2: Please insert a Aura ID or Pluginpart wont work."); CB2.Checked = false; } if (CB3.Checked && TBAura3.Text == "0") { Logging.Write("ItemForAura: Line 3: Please insert a Aura ID or Pluginpart wont work."); CB3.Checked = false; } if (CB4.Checked && TBAura4.Text == "0") { Logging.Write("ItemForAura: Line 4: Please insert a Aura ID or Pluginpart wont work."); CB4.Checked = false; } if (CB5.Checked && TBAura5.Text == "0") { Logging.Write("ItemForAura: Line 5: Please insert a Aura ID or Pluginpart wont work."); CB5.Checked = false; } if (CB6.Checked && TBAura6.Text == "0") { Logging.Write("ItemForAura: Line 6: Please insert a Aura ID or Pluginpart wont work."); CB6.Checked = false; } if (CB1.Checked && TBItem1.Text == "0") { Logging.Write("ItemForAura: Line 1: Please insert a Item ID or Pluginpart wont work."); CB1.Checked = false; } if (CB2.Checked && TBItem2.Text == "0") { Logging.Write("ItemForAura: Line 2: Please insert a Item ID or Pluginpart wont work."); CB2.Checked = false; } if (CB3.Checked && TBItem3.Text == "0") { Logging.Write("ItemForAura: Line 3: Please insert a Item ID or Pluginpart wont work."); CB3.Checked = false; } if (CB4.Checked && TBItem4.Text == "0") { Logging.Write("ItemForAura: Line 4: Please insert a Item ID or Pluginpart wont work."); CB4.Checked = false; } if (CB5.Checked && TBItem5.Text == "0") { Logging.Write("ItemForAura: Line 5: Please insert a Item ID or Pluginpart wont work."); CB5.Checked = false; } if (CB6.Checked && TBItem6.Text == "0") { Logging.Write("ItemForAura: Line 6: Please insert a Item ID or Pluginpart wont work."); CB6.Checked = false; } ItemForAura.Settings.Aura1 = TBAura1.Text; ItemForAura.Settings.Item1 = TBItem1.Text; ItemForAura.Settings.Quest11 = TBQuest11.Text; ItemForAura.Settings.Quest12 = TBQuest12.Text; ItemForAura.Settings.Quest13 = TBQuest13.Text; ItemForAura.Settings.Combat1 = CBCombat1.Checked; ItemForAura.Settings.Aura2 = TBAura2.Text; ItemForAura.Settings.Item2 = TBItem2.Text; ItemForAura.Settings.Quest21 = TBQuest21.Text; ItemForAura.Settings.Quest22 = TBQuest22.Text; ItemForAura.Settings.Quest23 = TBQuest23.Text; ItemForAura.Settings.Combat2 = CBCombat2.Checked; ItemForAura.Settings.Aura3 = TBAura3.Text; ItemForAura.Settings.Item3 = TBItem3.Text; ItemForAura.Settings.Quest31 = TBQuest31.Text; ItemForAura.Settings.Quest32 = TBQuest32.Text; ItemForAura.Settings.Quest33 = TBQuest33.Text; ItemForAura.Settings.Combat3 = CBCombat3.Checked; ItemForAura.Settings.Aura4 = TBAura4.Text; ItemForAura.Settings.Item4 = TBItem4.Text; ItemForAura.Settings.Quest41 = TBQuest41.Text; ItemForAura.Settings.Quest42 = TBQuest42.Text; ItemForAura.Settings.Quest43 = TBQuest43.Text; ItemForAura.Settings.Combat4 = CBCombat4.Checked; ItemForAura.Settings.Aura5 = TBAura5.Text; ItemForAura.Settings.Item5 = TBItem5.Text; ItemForAura.Settings.Quest51 = TBQuest51.Text; ItemForAura.Settings.Quest52 = TBQuest52.Text; ItemForAura.Settings.Quest53 = TBQuest53.Text; ItemForAura.Settings.Combat5 = CBCombat5.Checked; ItemForAura.Settings.Aura6 = TBAura6.Text; ItemForAura.Settings.Item6 = TBItem6.Text; ItemForAura.Settings.Quest61 = TBQuest61.Text; ItemForAura.Settings.Quest62 = TBQuest62.Text; ItemForAura.Settings.Quest63 = TBQuest63.Text; ItemForAura.Settings.Combat6 = CBCombat6.Checked; string File = "Plugins\\ItemForAuraQuesthelper\\"; Logging.Write("ItemForAura: SettingsSaved!"); XmlDocument xml; XmlElement root; XmlElement element; XmlText text; XmlComment xmlComment; string sPath = Process.GetCurrentProcess().MainModule.FileName; sPath = Path.GetDirectoryName(sPath); sPath = Path.Combine(sPath, File); if (!Directory.Exists(sPath)) { Logging.WriteDiagnostic("ItemForAura: Creating config directory"); Directory.CreateDirectory(sPath); } sPath = Path.Combine(sPath, "ItemForAura.config"); Logging.WriteDiagnostic("ItemForAura: Saving config file: {0}", sPath); xml = new XmlDocument(); XmlDeclaration dc = xml.CreateXmlDeclaration("1.0", "utf-8", null); xml.AppendChild(dc); xmlComment = xml.CreateComment( "=======================================================================\n" + ".CONFIG - This is the Config File For Item for Aura - Questhelper\n\n" + "XML file containing settings to customize in the Item for Aura - Questhelper Plugin\n" + "It is STRONGLY recommended you use the Configuration UI to change this\n" + "file instead of direct changein it here.\n" + "========================================================================"); //let's add the root element root = xml.CreateElement("ItemForAura"); root.AppendChild(xmlComment); //let's add another element (child of the root) element = xml.CreateElement("Active1"); text = xml.CreateTextNode(CB1.Checked.ToString()); element.AppendChild(text); root.AppendChild(element); //let's add another element (child of the root) element = xml.CreateElement("Active2"); text = xml.CreateTextNode(CB2.Checked.ToString()); element.AppendChild(text); root.AppendChild(element); //let's add another element (child of the root) element = xml.CreateElement("Active3"); text = xml.CreateTextNode(CB3.Checked.ToString()); element.AppendChild(text); root.AppendChild(element); //let's add another element (child of the root) element = xml.CreateElement("Active4"); text = xml.CreateTextNode(CB4.Checked.ToString()); element.AppendChild(text); root.AppendChild(element); //let's add another element (child of the root) element = xml.CreateElement("Active5"); text = xml.CreateTextNode(CB5.Checked.ToString()); element.AppendChild(text); root.AppendChild(element); //let's add another element (child of the root) element = xml.CreateElement("Active6"); text = xml.CreateTextNode(CB6.Checked.ToString()); element.AppendChild(text); root.AppendChild(element); //let's add another element (child of the root) element = xml.CreateElement("Item1"); text = xml.CreateTextNode(TBItem1.Text.ToString()); element.AppendChild(text); root.AppendChild(element); //let's add another element (child of the root) element = xml.CreateElement("Item2"); text = xml.CreateTextNode(TBItem2.Text.ToString()); element.AppendChild(text); root.AppendChild(element); //let's add another element (child of the root) element = xml.CreateElement("Item3"); text = xml.CreateTextNode(TBItem3.Text.ToString()); element.AppendChild(text); root.AppendChild(element); //let's add another element (child of the root) element = xml.CreateElement("Item4"); text = xml.CreateTextNode(TBItem4.Text.ToString()); element.AppendChild(text); root.AppendChild(element); //let's add another element (child of the root) element = xml.CreateElement("Item5"); text = xml.CreateTextNode(TBItem5.Text.ToString()); element.AppendChild(text); root.AppendChild(element); //let's add another element (child of the root) element = xml.CreateElement("Item6"); text = xml.CreateTextNode(TBItem6.Text.ToString()); element.AppendChild(text); root.AppendChild(element); //let's add another element (child of the root) element = xml.CreateElement("Aura1"); text = xml.CreateTextNode(TBAura1.Text.ToString()); element.AppendChild(text); root.AppendChild(element); //let's add another element (child of the root) element = xml.CreateElement("Aura2"); text = xml.CreateTextNode(TBAura2.Text.ToString()); element.AppendChild(text); root.AppendChild(element); //let's add another element (child of the root) element = xml.CreateElement("Aura3"); text = xml.CreateTextNode(TBAura3.Text.ToString()); element.AppendChild(text); root.AppendChild(element); //let's add another element (child of the root) element = xml.CreateElement("Aura4"); text = xml.CreateTextNode(TBAura4.Text.ToString()); element.AppendChild(text); root.AppendChild(element); //let's add another element (child of the root) element = xml.CreateElement("Aura5"); text = xml.CreateTextNode(TBAura5.Text.ToString()); element.AppendChild(text); root.AppendChild(element); //let's add another element (child of the root) element = xml.CreateElement("Aura6"); text = xml.CreateTextNode(TBAura6.Text.ToString()); element.AppendChild(text); root.AppendChild(element); //let's add another element (child of the root) element = xml.CreateElement("Quest11"); text = xml.CreateTextNode(TBQuest11.Text.ToString()); element.AppendChild(text); root.AppendChild(element); xml.AppendChild(root); //let's add another element (child of the root) element = xml.CreateElement("Quest21"); text = xml.CreateTextNode(TBQuest21.Text.ToString()); element.AppendChild(text); root.AppendChild(element); xml.AppendChild(root); //let's add another element (child of the root) element = xml.CreateElement("Quest31"); text = xml.CreateTextNode(TBQuest31.Text.ToString()); element.AppendChild(text); root.AppendChild(element); xml.AppendChild(root); //let's add another element (child of the root) element = xml.CreateElement("Quest41"); text = xml.CreateTextNode(TBQuest41.Text.ToString()); element.AppendChild(text); root.AppendChild(element); xml.AppendChild(root); //let's add another element (child of the root) element = xml.CreateElement("Quest51"); text = xml.CreateTextNode(TBQuest51.Text.ToString()); element.AppendChild(text); root.AppendChild(element); xml.AppendChild(root); //let's add another element (child of the root) element = xml.CreateElement("Quest61"); text = xml.CreateTextNode(TBQuest61.Text.ToString()); element.AppendChild(text); root.AppendChild(element); xml.AppendChild(root); //let's add another element (child of the root) element = xml.CreateElement("Quest12"); text = xml.CreateTextNode(TBQuest12.Text.ToString()); element.AppendChild(text); root.AppendChild(element); xml.AppendChild(root); //let's add another element (child of the root) element = xml.CreateElement("Quest22"); text = xml.CreateTextNode(TBQuest22.Text.ToString()); element.AppendChild(text); root.AppendChild(element); xml.AppendChild(root); //let's add another element (child of the root) element = xml.CreateElement("Quest32"); text = xml.CreateTextNode(TBQuest32.Text.ToString()); element.AppendChild(text); root.AppendChild(element); xml.AppendChild(root); //let's add another element (child of the root) element = xml.CreateElement("Quest42"); text = xml.CreateTextNode(TBQuest42.Text.ToString()); element.AppendChild(text); root.AppendChild(element); xml.AppendChild(root); //let's add another element (child of the root) element = xml.CreateElement("Quest52"); text = xml.CreateTextNode(TBQuest52.Text.ToString()); element.AppendChild(text); root.AppendChild(element); xml.AppendChild(root); //let's add another element (child of the root) element = xml.CreateElement("Quest62"); text = xml.CreateTextNode(TBQuest62.Text.ToString()); element.AppendChild(text); root.AppendChild(element); xml.AppendChild(root); //let's add another element (child of the root) element = xml.CreateElement("Quest13"); text = xml.CreateTextNode(TBQuest13.Text.ToString()); element.AppendChild(text); root.AppendChild(element); xml.AppendChild(root); //let's add another element (child of the root) element = xml.CreateElement("Quest23"); text = xml.CreateTextNode(TBQuest23.Text.ToString()); element.AppendChild(text); root.AppendChild(element); xml.AppendChild(root); //let's add another element (child of the root) element = xml.CreateElement("Quest33"); text = xml.CreateTextNode(TBQuest33.Text.ToString()); element.AppendChild(text); root.AppendChild(element); xml.AppendChild(root); //let's add another element (child of the root) element = xml.CreateElement("Quest43"); text = xml.CreateTextNode(TBQuest43.Text.ToString()); element.AppendChild(text); root.AppendChild(element); xml.AppendChild(root); //let's add another element (child of the root) element = xml.CreateElement("Quest53"); text = xml.CreateTextNode(TBQuest53.Text.ToString()); element.AppendChild(text); root.AppendChild(element); xml.AppendChild(root); //let's add another element (child of the root) element = xml.CreateElement("Quest63"); text = xml.CreateTextNode(TBQuest63.Text.ToString()); element.AppendChild(text); root.AppendChild(element); xml.AppendChild(root); //let's add another element (child of the root) element = xml.CreateElement("Combat1"); text = xml.CreateTextNode(CBCombat1.Checked.ToString()); element.AppendChild(text); root.AppendChild(element); //let's add another element (child of the root) element = xml.CreateElement("Combat2"); text = xml.CreateTextNode(CBCombat2.Checked.ToString()); element.AppendChild(text); root.AppendChild(element); //let's add another element (child of the root) element = xml.CreateElement("Combat3"); text = xml.CreateTextNode(CBCombat3.Checked.ToString()); element.AppendChild(text); root.AppendChild(element); //let's add another element (child of the root) element = xml.CreateElement("Combat4"); text = xml.CreateTextNode(CBCombat4.Checked.ToString()); element.AppendChild(text); root.AppendChild(element); //let's add another element (child of the root) element = xml.CreateElement("Combat5"); text = xml.CreateTextNode(CBCombat5.Checked.ToString()); element.AppendChild(text); root.AppendChild(element); //let's add another element (child of the root) element = xml.CreateElement("Combat6"); text = xml.CreateTextNode(CBCombat6.Checked.ToString()); element.AppendChild(text); root.AppendChild(element); System.IO.FileStream fs = new System.IO.FileStream(@sPath, System.IO.FileMode.Create, System.IO.FileAccess.Write); try { xml.Save(fs); fs.Close(); } catch (Exception np) { Logging.Write(np.Message); } }
private void AddConstraint(XmlNode aParent, List <SimpleSchema.SchemaObject> siblingSchemaObjects, TemplateConstraint aConstraint) { // If the constraint is a primitive, add a comment to the sample if (aConstraint.IsPrimitive) { XmlComment comment = _currentDocument.CreateComment("PRIMITIVE: " + aConstraint.PrimitiveText); XmlNode nonAttributeParent = GetNonAttributeParent(aParent); if (nonAttributeParent != null) { nonAttributeParent.AppendChild(comment); } } // If the constraint is not primitive and does not have a context, add an error comment to the sample else if (!aConstraint.IsPrimitive && string.IsNullOrEmpty(aConstraint.Context)) { XmlComment comment = _currentDocument.CreateComment("ERROR: Constraint " + aConstraint.Id.ToString() + " does not have a context."); aParent.AppendChild(comment); } else { // Splitting on / in case legacy data is exported that makes use of xpath in constraint contexts string[] lContextSplit = aConstraint.Context.Split('/'); XmlNode lCurrentNode = aParent; SimpleSchema.SchemaObject lSchemaObject = null; foreach (string lCurrentContextSplit in lContextSplit) { bool lIsAttribute = lCurrentContextSplit.StartsWith("@"); string lStrippedContext = lCurrentContextSplit.Replace("@", ""); // Add an error comment if an attribute is a child of another attribute (ex: "@root/@extension") if (lIsAttribute && lCurrentNode is XmlAttribute) { XmlComment comment = _currentDocument.CreateComment( "ERROR: An attribute cannot be a child of another attribute for constraint " + aConstraint.Id.ToString()); lCurrentNode.AppendChild(comment); break; } // Find the schema object associated with this constraint if (siblingSchemaObjects != null) { lSchemaObject = siblingSchemaObjects.SingleOrDefault( y => y.Name == lStrippedContext && y.IsAttribute == lIsAttribute); } // If the constraint is an attribute, add an attribute to the parent if (lIsAttribute) { XmlAttribute attribute = lCurrentNode.Attributes[lStrippedContext]; if (attribute == null) { attribute = _currentDocument.CreateAttribute(lStrippedContext); lCurrentNode.Attributes.Append(attribute); } if (!string.IsNullOrEmpty(aConstraint.Value)) { attribute.Value = aConstraint.Value; } else { attribute.Value = "XXX"; } lCurrentNode = attribute; } // Otherwise, create an element and add it to the parent else { XmlElement lNewContextElement = _currentDocument.CreateElement(lCurrentContextSplit); if (lSchemaObject != null) { foreach (SimpleSchema.SchemaObject lCurrentSchemaAttribute in lSchemaObject.Children.Where(y => y.IsAttribute)) { if (!lCurrentSchemaAttribute.Cardinality.StartsWith("1..")) { continue; } XmlAttribute newAttribute = _currentDocument.CreateAttribute(lCurrentSchemaAttribute.Name); lNewContextElement.Attributes.Append(newAttribute); if (!string.IsNullOrEmpty(lCurrentSchemaAttribute.FixedValue)) { newAttribute.Value = lCurrentSchemaAttribute.FixedValue; } else if (!string.IsNullOrEmpty(lCurrentSchemaAttribute.Value)) { newAttribute.Value = lCurrentSchemaAttribute.Value; } else { newAttribute.Value = "YYY"; } } } // Do not add elements to attributes if (!(lCurrentNode is XmlAttribute)) { lCurrentNode.AppendChild(lNewContextElement); lCurrentNode = lNewContextElement; } else { // Add a comment to the generated sample that indicates the problem string commentText = string.Format( "Error: Attribute contains an element. (CONF #: {0}, context: '{1}')", aConstraint.Id, !string.IsNullOrEmpty(aConstraint.Context) ? aConstraint.Context : "N/A"); XmlComment comment = this._currentDocument.CreateComment(commentText); if (lCurrentNode.ParentNode != null) { lCurrentNode.ParentNode.AppendChild(comment); } else { this._currentDocument.DocumentElement.AppendChild(comment); } } } if (lSchemaObject == null) { this.isSchemaValid = false; } } List <TemplateConstraint> childConstraints = aConstraint.ChildConstraints .OrderBy(y => y.Order) .ToList(); childConstraints.ForEach(y => AddConstraint(lCurrentNode, lSchemaObject != null ? lSchemaObject.Children : null, y)); if (lSchemaObject != null) { this.AddMissingRequiredData(lCurrentNode, lSchemaObject.Children); } if (lCurrentNode is XmlElement) { foreach (XmlNode childNode in lCurrentNode.ChildNodes) { if (childNode is XmlElement) { this.igTypePlugin.FillSampleData((XmlElement)childNode); } } } } }
public static void FirstChildOfNewComment() { var xmlDocument = new XmlDocument(); Assert.Null(xmlDocument.CreateComment("a comment").FirstChild); }
internal static void CreateAndSerialize() { XmlNamespaceManager namespaceManager = new XmlNamespaceManager(new NameTable()); const string NamespacePrefix = "dixin"; namespaceManager.AddNamespace(NamespacePrefix, "https://weblogs.asp.net/dixin"); XmlDocument document = new XmlDocument(namespaceManager.NameTable); XmlElement rss = document.CreateElement("rss"); rss.SetAttribute("version", "2.0"); XmlAttribute attribute = document.CreateAttribute( "xmlns", NamespacePrefix, namespaceManager.LookupNamespace("xmlns")); attribute.Value = namespaceManager.LookupNamespace(NamespacePrefix); rss.SetAttributeNode(attribute); document.AppendChild(rss); XmlElement channel = document.CreateElement("channel"); rss.AppendChild(channel); XmlElement item = document.CreateElement("item"); channel.AppendChild(item); XmlElement title = document.CreateElement("title"); title.InnerText = "LINQ via C#"; item.AppendChild(title); XmlElement link = document.CreateElement("link"); link.InnerText = "https://weblogs.asp.net/dixin/linq-via-csharp"; item.AppendChild(link); XmlElement description = document.CreateElement("description"); description.InnerXml = "<p>This is a tutorial of LINQ and functional programming. Hope it helps.</p>"; item.AppendChild(description); XmlElement pubDate = document.CreateElement("pubDate"); pubDate.InnerText = new DateTime(2009, 9, 7).ToString("r"); item.AppendChild(pubDate); XmlElement guid = document.CreateElement("guid"); guid.InnerText = "https://weblogs.asp.net/dixin/linq-via-csharp"; guid.SetAttribute("isPermaLink", "true"); item.AppendChild(guid); XmlElement category1 = document.CreateElement("category"); category1.InnerText = "C#"; item.AppendChild(category1); XmlNode category2 = category1.CloneNode(false); category2.InnerText = "LINQ"; item.AppendChild(category2); XmlComment comment = document.CreateComment("Comment."); item.AppendChild(comment); XmlElement source = document.CreateElement(NamespacePrefix, "source", namespaceManager.LookupNamespace(NamespacePrefix)); source.InnerText = "https://github.com/Dixin/CodeSnippets/tree/master/Dixin/Linq"; item.AppendChild(source); // Serialize XmlDocument to string. StringBuilder xmlString = new StringBuilder(); XmlWriterSettings settings = new XmlWriterSettings { Indent = true, IndentChars = " ", OmitXmlDeclaration = true }; using (XmlWriter writer = XmlWriter.Create(xmlString, settings)) { document.Save(writer); } // rssItem.ToString() returns "System.Xml.XmlElement". // rssItem.OuterXml returns a single line of XML text. xmlString.WriteLine(); }
public static void ElementNodeWithOneChildDeleteItInsertTwoNewChildren() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<top><child /></top>"); xmlDocument.DocumentElement.RemoveChild(xmlDocument.DocumentElement.FirstChild); var newNode1 = xmlDocument.CreateTextNode("text node"); var newNode2 = xmlDocument.CreateComment("comment here"); xmlDocument.DocumentElement.AppendChild(newNode1); xmlDocument.DocumentElement.AppendChild(newNode2); Assert.NotNull(xmlDocument.DocumentElement.FirstChild); Assert.Same(newNode1, xmlDocument.DocumentElement.FirstChild); }
/// <summary> /// Add a dependency to Versions.props. This has the form: /// <!-- Package names --> /// <PropertyGroup> /// <MicrosoftDotNetApiCompatPackage>Microsoft.DotNet.ApiCompat</MicrosoftDotNetApiCompatPackage> /// </PropertyGroup> /// /// <!-- Package versions --> /// <PropertyGroup> /// <MicrosoftDotNetApiCompatPackageVersion>1.0.0-beta.18478.5</MicrosoftDotNetApiCompatPackageVersion> /// </PropertyGroup> /// /// See https://github.com/dotnet/arcade/blob/master/Documentation/DependencyDescriptionFormat.md for more /// information. /// </summary> /// <param name="repo">Path to Versions.props file</param> /// <param name="dependency">Dependency information to add.</param> /// <returns>Async task.</returns> public async Task AddDependencyToVersionsPropsAsync(string repo, string branch, DependencyDetail dependency) { XmlDocument versionProps = await ReadVersionPropsAsync(repo, null); string documentNamespaceUri = versionProps.DocumentElement.NamespaceURI; string packageNameElementName = VersionFiles.GetVersionPropsPackageElementName(dependency.Name); string packageVersionElementName = VersionFiles.GetVersionPropsPackageVersionElementName(dependency.Name); string packageVersionAlternateElementName = VersionFiles.GetVersionPropsAlternatePackageVersionElementName( dependency.Name); // Select elements by local name, since the Project (DocumentElement) element often has a default // xmlns set. XmlNodeList propertyGroupNodes = versionProps.DocumentElement.SelectNodes($"//*[local-name()='PropertyGroup']"); XmlNode newPackageNameElement = versionProps.CreateElement(packageNameElementName, documentNamespaceUri); newPackageNameElement.InnerText = dependency.Name; bool addedPackageVersionElement = false; bool addedPackageNameElement = false; // There can be more than one property group. Find the appropriate one containing an existing element of // the same type, and add it to the parent. foreach (XmlNode propertyGroupNode in propertyGroupNodes) { if (propertyGroupNode.HasChildNodes) { foreach (XmlNode propertyNode in propertyGroupNode.ChildNodes) { if (!addedPackageVersionElement && propertyNode.Name.EndsWith(VersionFiles.VersionPropsVersionElementSuffix)) { XmlNode newPackageVersionElement = versionProps.CreateElement( packageVersionElementName, documentNamespaceUri); newPackageVersionElement.InnerText = dependency.Version; propertyGroupNode.AppendChild(newPackageVersionElement); addedPackageVersionElement = true; break; } // Test for alternate suffixes. This will eventually be replaced by repo-level configuration: // https://github.com/dotnet/arcade/issues/1095 else if (!addedPackageVersionElement && propertyNode.Name.EndsWith( VersionFiles.VersionPropsAlternateVersionElementSuffix)) { XmlNode newPackageVersionElement = versionProps.CreateElement( packageVersionAlternateElementName, documentNamespaceUri); newPackageVersionElement.InnerText = dependency.Version; propertyGroupNode.AppendChild(newPackageVersionElement); addedPackageVersionElement = true; break; } else if (!addedPackageNameElement && propertyNode.Name.EndsWith(VersionFiles.VersionPropsPackageElementSuffix)) { propertyGroupNode.AppendChild(newPackageNameElement); addedPackageNameElement = true; break; } } if (addedPackageVersionElement && addedPackageNameElement) { break; } } } // Add the property groups if none were present if (!addedPackageVersionElement) { // If the repository doesn't have any package version element, then // use the non-alternate element name. XmlNode newPackageVersionElement = versionProps.CreateElement(packageVersionElementName, documentNamespaceUri); newPackageVersionElement.InnerText = dependency.Version; XmlNode propertyGroupElement = versionProps.CreateElement("PropertyGroup", documentNamespaceUri); XmlNode propertyGroupCommentElement = versionProps.CreateComment("Package versions"); versionProps.DocumentElement.AppendChild(propertyGroupCommentElement); versionProps.DocumentElement.AppendChild(propertyGroupElement); propertyGroupElement.AppendChild(newPackageVersionElement); } if (!addedPackageNameElement) { XmlNode propertyGroupElement = versionProps.CreateElement("PropertyGroup", documentNamespaceUri); XmlNode propertyGroupCommentElement = versionProps.CreateComment("Package names"); versionProps.DocumentElement.AppendChild(propertyGroupCommentElement); versionProps.DocumentElement.AppendChild(propertyGroupElement); propertyGroupElement.AppendChild(newPackageNameElement); } // TODO: This should not be done here. This should return some kind of generic file container to the caller, // who will gather up all updates and then call the git client to write the files all at once: // https://github.com/dotnet/arcade/issues/1095. Today this is only called from the Local interface so // it's okay for now. var file = new GitFile(VersionFiles.VersionProps, versionProps); await _gitClient.PushFilesAsync(new List <GitFile> { file }, repo, branch, $"Add {dependency} to " + $"'{VersionFiles.VersionProps}'"); _logger.LogInformation( $"Dependency '{dependency.Name}' with version '{dependency.Version}' successfully added to " + $"'{VersionFiles.VersionProps}'"); }
public static void CommentNode() { var xmlDocument = new XmlDocument(); var node = xmlDocument.CreateComment("comment"); Assert.Equal("comment", node.Value); node.Value = "new comment"; Assert.Equal("new comment", node.Value); }
public override void AddComment(XmlNode node, string comment) { node.AppendChild(_doc.CreateComment(comment)); }