コード例 #1
0
ファイル: RDFTriX.cs プロジェクト: vlslavik/RDFSharp
        /// <summary>
        /// Serializes the given store to the given stream using TriX data format.
        /// </summary>
        internal static void Serialize(RDFStore store, Stream outputStream)
        {
            try {
                #region serialize
                using (XmlTextWriter trixWriter = new XmlTextWriter(outputStream, Encoding.UTF8)) {
                    XmlDocument trixDoc = new XmlDocument();
                    trixWriter.Formatting = Formatting.Indented;

                    #region xmlDecl
                    XmlDeclaration trixDecl = trixDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
                    trixDoc.AppendChild(trixDecl);
                    #endregion

                    #region trixRoot
                    XmlNode      trixRoot       = trixDoc.CreateNode(XmlNodeType.Element, "TriX", null);
                    XmlAttribute trixRootNS     = trixDoc.CreateAttribute("xmlns");
                    XmlText      trixRootNSText = trixDoc.CreateTextNode("http://www.w3.org/2004/03/trix/trix-1/");
                    trixRootNS.AppendChild(trixRootNSText);
                    trixRoot.Attributes.Append(trixRootNS);

                    #region graphs
                    foreach (var graph             in store.ExtractGraphs())
                    {
                        XmlNode graphElement     = trixDoc.CreateNode(XmlNodeType.Element, "graph", null);
                        XmlNode graphUriElement  = trixDoc.CreateNode(XmlNodeType.Element, "uri", null);
                        XmlText graphUriElementT = trixDoc.CreateTextNode(graph.ToString());
                        graphUriElement.AppendChild(graphUriElementT);
                        graphElement.AppendChild(graphUriElement);

                        #region triple
                        foreach (var t in graph)
                        {
                            XmlNode tripleElement = trixDoc.CreateNode(XmlNodeType.Element, "triple", null);

                            #region subj
                            XmlNode subjElement = (((RDFResource)t.Subject).IsBlank ? trixDoc.CreateNode(XmlNodeType.Element, "id", null)  :
                                                   trixDoc.CreateNode(XmlNodeType.Element, "uri", null));
                            XmlText subjElementText = trixDoc.CreateTextNode(t.Subject.ToString());
                            subjElement.AppendChild(subjElementText);
                            tripleElement.AppendChild(subjElement);
                            #endregion

                            #region pred
                            XmlNode uriElementP = trixDoc.CreateNode(XmlNodeType.Element, "uri", null);
                            XmlText uriTextP    = trixDoc.CreateTextNode(t.Predicate.ToString());
                            uriElementP.AppendChild(uriTextP);
                            tripleElement.AppendChild(uriElementP);
                            #endregion

                            #region object
                            if (t.TripleFlavor == RDFModelEnums.RDFTripleFlavors.SPO)
                            {
                                XmlNode objElement = (((RDFResource)t.Object).IsBlank ? trixDoc.CreateNode(XmlNodeType.Element, "id", null)  :
                                                      trixDoc.CreateNode(XmlNodeType.Element, "uri", null));
                                XmlText objElementText = trixDoc.CreateTextNode(t.Object.ToString());
                                objElement.AppendChild(objElementText);
                                tripleElement.AppendChild(objElement);
                            }
                            #endregion

                            #region literal
                            else
                            {
                                #region plain literal
                                if (t.Object is RDFPlainLiteral)
                                {
                                    XmlNode plainLiteralElement = trixDoc.CreateNode(XmlNodeType.Element, "plainLiteral", null);
                                    if (((RDFPlainLiteral)t.Object).Language != String.Empty)
                                    {
                                        XmlAttribute xmlLang     = trixDoc.CreateAttribute(RDFVocabulary.XML.PREFIX + ":lang", RDFVocabulary.XML.BASE_URI);
                                        XmlText      xmlLangText = trixDoc.CreateTextNode(((RDFPlainLiteral)t.Object).Language);
                                        xmlLang.AppendChild(xmlLangText);
                                        plainLiteralElement.Attributes.Append(xmlLang);
                                    }
                                    XmlText plainLiteralText = trixDoc.CreateTextNode(RDFModelUtilities.EscapeControlCharsForXML(HttpUtility.HtmlDecode(((RDFLiteral)t.Object).Value)));
                                    plainLiteralElement.AppendChild(plainLiteralText);
                                    tripleElement.AppendChild(plainLiteralElement);
                                }
                                #endregion

                                #region typed literal
                                else
                                {
                                    XmlNode      typedLiteralElement = trixDoc.CreateNode(XmlNodeType.Element, "typedLiteral", null);
                                    XmlAttribute datatype            = trixDoc.CreateAttribute("datatype");
                                    XmlText      datatypeText        = trixDoc.CreateTextNode(RDFModelUtilities.GetDatatypeFromEnum(((RDFTypedLiteral)t.Object).Datatype));
                                    datatype.AppendChild(datatypeText);
                                    typedLiteralElement.Attributes.Append(datatype);
                                    XmlText typedLiteralText = trixDoc.CreateTextNode(RDFModelUtilities.EscapeControlCharsForXML(HttpUtility.HtmlDecode(((RDFLiteral)t.Object).Value)));
                                    typedLiteralElement.AppendChild(typedLiteralText);
                                    tripleElement.AppendChild(typedLiteralElement);
                                }
                                #endregion
                            }
                            #endregion

                            graphElement.AppendChild(tripleElement);
                        }
                        #endregion

                        trixRoot.AppendChild(graphElement);
                    }
                    #endregion

                    trixDoc.AppendChild(trixRoot);
                    #endregion

                    trixDoc.Save(trixWriter);
                }
                #endregion
            }
            catch (Exception ex) {
                throw new RDFStoreException("Cannot serialize TriX because: " + ex.Message, ex);
            }
        }
コード例 #2
0
        static void Main(string[] args)
        {
            XmlDocument doc      = new XmlDocument();
            string      filename = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "myfile.xml");

            doc.Load(filename);

            XmlElement   root        = doc.DocumentElement;
            XmlNode      nodeVeicolo = root.FirstChild;
            XmlAttribute attrTarga   = nodeVeicolo.Attributes["targa"];
            string       targa       = attrTarga.Value;

            attrTarga.Value = "XY";

            XmlNode nodeMarca   = nodeVeicolo.FirstChild;
            string  marca       = nodeMarca.Value;
            XmlNode nodeModello = nodeMarca.NextSibling;
            string  modello     = nodeModello.InnerXml;

            nodeModello.InnerXml = "Spider";

            Console.WriteLine(doc.InnerXml);

            string xml = @"<?xml version=""1.0"" encoding=""utf-8"" ?>
                <!-- contiene dati sui veicoli -->
                <veicoli>
                    <veicolo targa=""AB123CD"">
                        <marca>Alfa Romeo</marca>
                        <modello>GT</modello>
                    </veicolo>
                </veicoli>";

            doc.LoadXml(xml);

            doc.Save(filename);

            XmlDocument    doc2 = new XmlDocument();
            XmlDeclaration decl = doc2.CreateXmlDeclaration("1.0", "UTF-8", null);

            doc2.AppendChild(decl);

            XmlComment comment = doc2.CreateComment("contiene dati sui veicoli");

            doc2.AppendChild(comment);

            XmlElement nodVeicoli = doc2.CreateElement("veicoli");

            XmlElement nodVeicolo = doc2.CreateElement("veicolo");

            nodVeicolo.SetAttribute("targa", "AB123CD");
            XmlElement nodMarca = doc2.CreateElement("marca");

            nodMarca.InnerText = "Alfa Romeo";
            nodVeicolo.AppendChild(nodMarca);


            XmlElement nodModello = doc2.CreateElement("modello");
            XmlText    textNode   = doc2.CreateTextNode("<GT>");

            nodModello.AppendChild(textNode);

            nodVeicolo.AppendChild(nodModello);

            nodVeicoli.AppendChild(nodVeicolo);
            doc2.AppendChild(nodVeicoli);

            string xml2 = doc2.OuterXml;

            doc2.Save("myfile2.xml");

            Console.WriteLine("---- XmlReader ----");

            using (XmlTextReader txtReader = new XmlTextReader(filename))
            {
                while (txtReader.Read())
                {
                    Console.Write(new string(' ', txtReader.Depth));
                    Console.WriteLine("{0}: {1} {2}", txtReader.NodeType, txtReader.Name, txtReader.Value);
                }
            }

            XmlReaderSettings settings = new XmlReaderSettings();

            settings.IgnoreComments   = true;
            settings.IgnoreWhitespace = true;

            using (XmlReader reader = XmlReader.Create(new StreamReader(filename), settings))
            {
                while (reader.Read())
                {
                    Console.Write(new string(' ', reader.Depth));
                    switch (reader.NodeType)
                    {
                    case XmlNodeType.XmlDeclaration:
                        string version = reader.GetAttribute("version");
                        reader.MoveToAttribute("version");
                        Console.WriteLine("version={0}", reader.Value);
                        while (reader.MoveToNextAttribute())
                        {
                            Console.WriteLine("{0}={1}", reader.Name, reader.Value);
                        }
                        break;

                    case XmlNodeType.Attribute:
                        Console.WriteLine(reader.NodeType + ": " + reader.Name + " " + reader.Value);
                        break;

                    default:
                        Console.WriteLine(reader.NodeType + ": " + reader.Name + " " + reader.Value);
                        break;
                    }
                }
            }

            XmlWriterSettings ws = new XmlWriterSettings()
            {
                Indent = true, Encoding = UTF8Encoding.UTF8
            };

            using (XmlWriter writer = XmlWriter.Create("generated.xml", ws))
            {
                writer.WriteComment("questa è una prova");
                writer.WriteStartElement("veicoli");
                writer.WriteStartElement("veicolo");
                writer.WriteAttributeString("targa", "AB123DC");
                writer.WriteElementString("marca", "Alfa Romeo");
                writer.WriteElementString("modello", "GT");
                writer.WriteEndElement();
                writer.WriteEndElement();
            }
        }
コード例 #3
0
        static void ex1()
        {
            XmlDocument    doc            = new XmlDocument();
            XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration("1.0", "utf-8", null);

            XmlElement   films = doc.CreateElement("Films");
            XmlAttribute list  = doc.CreateAttribute("FilmName");

            list.InnerText = "Список фильмов";
            films.Attributes.Append(list);

            XmlElement name = doc.CreateElement("Film");

            name.InnerText = "Алита боевой ангел";
            XmlElement genre = doc.CreateElement("Genre");

            genre.InnerText = "Фантастика";
            XmlElement rating = doc.CreateElement("Rating");

            rating.InnerText = "7.2";
            XmlElement body = doc.CreateElement("body");

            body.InnerText = "Действие фильма происходит через 300 лет после Великой войны в XXVI веке. Доктор Идо находит останки женщины-киборга. После починки киборг ничего не помнит, но обнаруживает, что в состоянии пользоваться боевыми приемами киборгов. Начинаются поиски утерянных воспоминаний.";

            films.AppendChild(name);
            films.AppendChild(genre);
            films.AppendChild(rating);
            films.AppendChild(body);
            doc.AppendChild(films);
            doc.Save("films.xml");

            XmlElement name1 = doc.CreateElement("Film");

            name1.InnerText = "Зеленая книга";
            XmlElement genre1 = doc.CreateElement("Genre");

            genre1.InnerText = "Комедия/драма";
            XmlElement rating1 = doc.CreateElement("Rating");

            rating1.InnerText = "8.4";
            XmlElement body1 = doc.CreateElement("body");

            body1.InnerText = "1960-е годы. После закрытия нью-йоркского ночного клуба на ремонт вышибала Тони по прозвищу Болтун ищет подработку на пару месяцев. Как раз в это время Дон Ширли, утонченный светский лев, богатый и талантливый чернокожий музыкант, исполняющий классическую музыку, собирается в турне по южным штатам, где ещё сильны расистские убеждения и царит сегрегация. Он нанимает Тони в качестве водителя, телохранителя и человека, способного решать текущие проблемы. У этих двоих так мало общего, и эта поездка навсегда изменит жизнь обоих.";

            films.AppendChild(name1);
            films.AppendChild(genre1);
            films.AppendChild(rating1);
            films.AppendChild(body1);
            doc.AppendChild(films);
            doc.Save("films.xml");


            XmlElement name2 = doc.CreateElement("Film");

            name2.InnerText = "Побег из Шоушенка";
            XmlElement genre2 = doc.CreateElement("Genre");

            genre2.InnerText = "Драма";
            XmlElement rating2 = doc.CreateElement("Rating");

            rating2.InnerText = "9.1";
            XmlElement body2 = doc.CreateElement("body");

            body2.InnerText = "Бухгалтер Энди Дюфрейн обвинен в убийстве собственной жены и ее любовника. Оказавшись в тюрьме под названием Шоушенк, он сталкивается с жестокостью и беззаконием, царящими по обе стороны решетки. Каждый, кто попадает в эти стены, становится их рабом до конца жизни. Но Энди, обладающий живым умом и доброй душой, находит подход как к заключенным, так и к охранникам, добиваясь их особого к себе расположения.";

            films.AppendChild(name2);
            films.AppendChild(genre2);
            films.AppendChild(rating2);
            films.AppendChild(body2);
            doc.AppendChild(films);
            doc.Save("films.xml");


            XmlElement name3 = doc.CreateElement("Film");

            name3.InnerText = "Призрак в доспехах";
            XmlElement genre3 = doc.CreateElement("Genre");

            genre3.InnerText = "Аниме";
            XmlElement rating3 = doc.CreateElement("Rating");

            rating3.InnerText = "7.9";
            XmlElement body3 = doc.CreateElement("body");

            body3.InnerText = "2029 год. Границы между государствами окончательно рухнули, благодаря повсеместно распространившимся компьютерным сетям и кибер-технологиям. Когда давно разыскиваемый хакер по кличке Кукловод начинает вмешиваться в политику, 9-й Отдел Министерства Общественной безопасности, группа кибернетически модифицированных полицейских, получает задание найти и остановить хакера. Но в ходе расследования возникает вопрос: кто же такой Кукловод в том мире где грань между человеком и машиной практически стерта?";

            films.AppendChild(name3);
            films.AppendChild(genre3);
            films.AppendChild(rating3);
            films.AppendChild(body3);
            doc.AppendChild(films);
            doc.Save("films.xml");


            XmlElement name4 = doc.CreateElement("Film");

            name4.InnerText = "Настоящий детектив";
            XmlElement genre4 = doc.CreateElement("Genre");

            genre4.InnerText = "Детектив/Криминал";
            XmlElement rating4 = doc.CreateElement("Rating");

            rating4.InnerText = "8.7";
            XmlElement body4 = doc.CreateElement("body");

            body4.InnerText = "Первый сезон. В Луизиане в 1995 году происходит странное убийство девушки. В 2012 году дело об убийстве 1995г. повторно открывают, так как произошло похожее убийство. Дабы лучше продвинуться в расследовании, полиция решает допросить бывших детективов, которые работали над делом в 1995г.";

            films.AppendChild(name4);
            films.AppendChild(genre4);
            films.AppendChild(rating4);
            films.AppendChild(body4);
            doc.AppendChild(films);
            doc.Save("films.xml");
        }
コード例 #4
0
        public static bool Save()
        {
            SaveFileDialog dialog = new SaveFileDialog();

            dialog.AddExtension = true;
            dialog.FileName     = "Debug_Log_Results";
            dialog.Filter       = "Log files (*.log)|*.log|XML Log files (*.xml)|*.xml";

            dialog.InitialDirectory = Program.opt.DefaultOutputPath.ToString();
            if (dialog.ShowDialog() != DialogResult.OK)
            {
                MessageBox.Show("Error Saving Log File or No Filename Given!");
                return(false);
            }

            if (dialog.FilterIndex == 1)
            {
                StreamWriter LogFile = File.CreateText(dialog.FileName.ToString());
                LogFile.Write(LogResults.ToString());
                LogFile.Close();
            }
            else if (dialog.FilterIndex == 2)
            {
                // Save as XML instead!
                XmlDocument    dom  = new XmlDocument();
                XmlDeclaration decl = dom.CreateXmlDeclaration("1.0", "utf-8", null);
                dom.AppendChild(decl);
                XmlElement Root      = dom.CreateElement("DebugLogFileResults");
                XmlElement SheetInfo = dom.CreateElement("Sheet_Information");
                XmlElement Title     = dom.CreateElement("Title");
                Title.InnerText = "POL Debug.Log Parser Results File";
                SheetInfo.AppendChild(Title);
                XmlElement LogFileElement = dom.CreateElement("LogFile");
                LogFileElement.InnerText = DebugLogParsed.ToString();
                SheetInfo.AppendChild(LogFileElement);
                XmlElement ParseDate = dom.CreateElement("Date");
                ParseDate.InnerText = DateTime.Now.ToString();
                SheetInfo.AppendChild(ParseDate);
                Root.AppendChild(SheetInfo);

                XmlElement ParseResultsElement  = dom.CreateElement("Parse_Results");
                XmlElement ScriptResultsElement = dom.CreateElement("Script_Results");
                foreach (System.Collections.ArrayList ScriptInstance in ScriptResults)
                {
                    XmlElement Instance   = dom.CreateElement("Script_Instance");
                    XmlElement ScriptName = dom.CreateElement("Script");
                    ScriptName.InnerText = ScriptInstance[0].ToString();
                    Instance.AppendChild(ScriptName);
                    XmlElement LSTLine = dom.CreateElement("LST_Line");
                    LSTLine.InnerText = ScriptInstance[1].ToString();
                    Instance.AppendChild(LSTLine);
                    ParseResultsElement.AppendChild(Instance);
                    XmlElement FunctionName = dom.CreateElement("Function_Name");
                    FunctionName.InnerText = ScriptInstance[2].ToString();
                    Instance.AppendChild(FunctionName);
                    ParseResultsElement.AppendChild(Instance);
                    XmlElement Error_Return = dom.CreateElement("Error_Return");
                    Error_Return.InnerText = ScriptInstance[3].ToString();
                    Instance.AppendChild(Error_Return);
                    ScriptResultsElement.AppendChild(Instance);
                }
                ParseResultsElement.AppendChild(ScriptResultsElement);

                XmlElement ConfigResultsElement = dom.CreateElement("Config_Results");
                foreach (string ConfigEntry in ConfigResults)
                {
                    XmlElement Instance   = dom.CreateElement("Missing_Config");
                    XmlElement ConfigName = dom.CreateElement("Config");
                    ConfigName.InnerText = ConfigEntry;
                    Instance.AppendChild(ConfigName);
                    ConfigResultsElement.AppendChild(Instance);
                }
                ParseResultsElement.AppendChild(ConfigResultsElement);

                Root.AppendChild(ParseResultsElement);
                dom.AppendChild(Root);
                dom.Save(dialog.FileName.ToString());
            }

            dialog.Dispose();
            MessageBox.Show("Log Successfully Saved!");
            return(true);
        }
コード例 #5
0
        protected void btnExportXml_Click(object sender, EventArgs e)
        {
            // Populate report
            PopulateSummary();

            var documentDirectory = String.Format("{0}\\Temp\\", System.AppDomain.CurrentDomain.BaseDirectory);
            var ns = ""; // urn:pvims-org:v3

            string contentXml = string.Empty;
            string destName   = string.Format("ReportDrug_{0}.xml", DateTime.Now.ToString("yyyyMMddhhmmsss"));
            string destFile   = string.Format("{0}{1}", documentDirectory, destName);

            // Create document
            XmlDocument  xmlDoc = new XmlDocument();
            XmlNode      rootNode;
            XmlNode      filterNode;
            XmlNode      contentHeadNode;
            XmlNode      contentNode;
            XmlNode      contentValueNode;
            XmlAttribute attrib;

            XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);

            xmlDoc.AppendChild(xmlDeclaration);

            rootNode         = xmlDoc.CreateElement("PViMS_DrugReport", ns);
            attrib           = xmlDoc.CreateAttribute("CreatedDate");
            attrib.InnerText = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
            rootNode.Attributes.Append(attrib);

            // Write filter
            filterNode = xmlDoc.CreateElement("Filter", ns);
            rootNode.AppendChild(filterNode);

            // Write content
            var rowCount  = 0;
            var cellCount = 0;

            contentHeadNode  = xmlDoc.CreateElement("Content", ns);
            attrib           = xmlDoc.CreateAttribute("RowCount");
            attrib.InnerText = (dt_basic.Rows.Count - 1).ToString();

            ArrayList headerArray = new ArrayList();

            foreach (TableRow row in dt_basic.Rows)
            {
                rowCount   += 1;
                cellCount   = 0;
                contentNode = xmlDoc.CreateElement("Row", ns);

                foreach (TableCell cell in row.Cells)
                {
                    int[] ignore = { 2 };

                    if (!ignore.Contains(cellCount))
                    {
                        cellCount += 1;

                        if (rowCount == 1)
                        {
                            headerArray.Add(cell.Text);
                        }
                        else
                        {
                            var nodeName = Regex.Replace(headerArray[cellCount - 1].ToString().Replace(" ", ""), "[^0-9a-zA-Z]+", "");
                            contentValueNode           = xmlDoc.CreateElement(nodeName, ns);
                            contentValueNode.InnerText = cell.Text;

                            contentNode.AppendChild(contentValueNode);
                        }
                    }
                }
                if (contentNode.ChildNodes.Count > 0)
                {
                    contentHeadNode.AppendChild(contentNode);
                }
            }
            rootNode.AppendChild(contentHeadNode);
            xmlDoc.AppendChild(rootNode);

            contentXml = FormatXML(xmlDoc);
            WriteXML(destFile, contentXml);

            Response.Clear();
            Response.Buffer          = true;
            Response.ContentEncoding = Encoding.UTF8;
            Response.ContentType     = "application/xml";
            Response.AddHeader("content-disposition", String.Format("attachment;filename={0}", destName));
            Response.Charset     = "";
            this.EnableViewState = false;

            Response.WriteFile(destFile);
            Response.End();
        }
コード例 #6
0
        public static void SaveClientPath(string location, string fileName, string fileVersion)
        {
            XmlDocument document    = new XmlDocument();
            XmlElement  clientPaths = null;
            bool        exists      = false;

            if (File.Exists(location))
            {
                document.Load(location);
                clientPaths = document["clientPaths"];
                foreach (XmlElement clientPath in clientPaths)
                {
                    if (clientPath.GetAttribute("location").Equals(fileName))
                    {
                        if (document["clientPaths"].FirstChild != clientPath)
                        {
                            document["clientPaths"].RemoveChild(clientPath);
                            document["clientPaths"].InsertBefore(
                                clientPath,
                                document["clientPaths"].FirstChild);
                        }
                        document.Save(location);
                        if (!clientPath.GetAttribute("version").Equals(fileVersion))
                        {
                            clientPath.SetAttribute("version", fileVersion);
                            document.Save(location);
                            exists = true;
                            break;
                        }
                        exists = true;
                        break;
                    }
                }
            }
            else
            {
                XmlDeclaration Declaration = document.CreateXmlDeclaration("1.0", "", "");
                document.AppendChild(Declaration);
                clientPaths = document.CreateElement("clientPaths");
                document.AppendChild(clientPaths);
            }
            if (!exists)
            {
                XmlElement   clientPath   = document.CreateElement("clientPath");
                XmlAttribute locationAttr = document.CreateAttribute("location");
                locationAttr.InnerText = fileName;
                XmlAttribute version = document.CreateAttribute("version");
                version.InnerText = fileVersion;

                clientPath.Attributes.Append(locationAttr);
                clientPath.Attributes.Append(version);
                clientPaths.AppendChild(clientPath);

                if (!Directory.Exists(Constants.AppDataPath))
                {
                    Directory.CreateDirectory(Constants.AppDataPath);
                }

                document.Save(location);
            }
        }
コード例 #7
0
        private byte[] GetNotifyMessageXml(bool IsMulity)
        {
            byte[] buf = null;

            XmlDocument    doc = new XmlDocument();
            XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "UTF-8", null);

            doc.AppendChild(dec);

            XmlElement root = doc.CreateElement("CloudPrint");

            XmlNode node = doc.CreateElement("Notify");

            XmlElement elementPort = doc.CreateElement("Port");

            Debug.Assert(this.mTCPServer != null);
            if (this.mTCPServer == null)
            {
                elementPort.InnerText = "10001";
            }
            else
            {
                elementPort.InnerText = ((IPEndPoint)(this.mTCPServer.LocalEndPoint)).Port.ToString();
            }

            node.AppendChild(elementPort);

            XmlElement elementHostType = doc.CreateElement("HostType");

            elementHostType.InnerText = "1";
            node.AppendChild(elementHostType);

            XmlElement elementHostName = doc.CreateElement("HostName");

            elementHostName.InnerText = "pc";
            node.AppendChild(elementHostName);

            XmlElement elementPhoneType = doc.CreateElement("PhoneType");

            elementPhoneType.InnerText = "n";
            node.AppendChild(elementPhoneType);

            XmlElement elementPcName = doc.CreateElement("PcName");

            elementPcName.InnerText = Dns.GetHostName();
            node.AppendChild(elementPcName);

            XmlElement elementPhoneNameAlias = doc.CreateElement("PhoneNameAlias");

            elementPhoneNameAlias.InnerText = "n";
            node.AppendChild(elementPhoneNameAlias);

            {
                XmlElement element = doc.CreateElement("MachineMac");
                element.InnerText = LibCui.GetLocalMacAddress();
                node.AppendChild(element);
            }

            XmlElement elementMultiply = doc.CreateElement("Multiply");

            if (IsMulity)
            {
                elementMultiply.InnerText = "true";
            }
            else
            {
                elementMultiply.InnerText = "false";
            }

            node.AppendChild(elementMultiply);



            root.AppendChild(node);

            doc.AppendChild(root);
            buf = Encoding.UTF8.GetBytes(doc.InnerXml);
            // doc.Save("Notify.xml");
            return(buf);
        }
コード例 #8
0
        /// <summary>
        /// 生成报表样式
        /// </summary>
        /// <param name="columns">报表中显示的列,有name、text、type 列,name:绑定的数据集中的列名;text:报表中显示的列名;type:数据集中列的数据类型 </param>
        /// <param name="merger">报表中需要合并相同内容的从0开始的列序号,多个列以“,”隔开</param>
        /// <returns>true 保存成功,false 保存失败 </returns>
        public bool SaveXML(DataTable columns, string merger)
        {
            try
            {
                #region [获取报表列信息]
                if (_savePath == "" || columns == null)
                {
                    return(false);
                }
                DataTable     dscolumn = new DataTable();
                ReportDataDAL _repdall = new ReportDataDAL();
                #endregion

                #region [局部变量]
                int columncount = columns.Rows.Count;
                //当前报表中已经处理的行数,仅供行编号使用
                int execount = 0;
                //临时列编号
                int colid = 0;
                //数据表格部分起始编号
                int startid = 0;
                if (_addReserved)
                {
                    startid = 1;
                }
                #endregion

                #region [创建XML头]
                XmlDocument    doc = new XmlDocument();
                XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);
                doc.AppendChild(dec);
                #endregion

                #region [Report]
                //创建一个根节点(一级)
                XmlElement Report = doc.CreateElement("Report");
                doc.AppendChild(Report);
                #endregion

                #region [WorkSheet]
                //创建节点(二级)
                XmlElement WorkSheet = doc.CreateElement("WorkSheet");
                WorkSheet.SetAttribute("name", merger);//将需要合并的列存入工作的name中
                WorkSheet.SetAttribute("isDefaultPrint", "true");
                Report.AppendChild(WorkSheet);

                #region [Properties]
                //创建节点(三级)
                XmlElement Properties = doc.CreateElement("Properties");
                WorkSheet.AppendChild(Properties);
                #endregion

                #region [BackGround]
                XmlElement BackGround = doc.CreateElement("BackGround");
                BackGround.SetAttribute("bgColor", "#FFFFFF");
                BackGround.SetAttribute("arange", "tile");
                BackGround.SetAttribute("alpha", "255");
                Properties.AppendChild(BackGround);
                #endregion

                #region [DefaultTD]
                XmlElement DefaultTD = doc.CreateElement("DefaultTD");
                XmlElement TD        = doc.CreateElement("TD");
                TD.SetAttribute("fontIndex", "1");
                TD.SetAttribute("textColor", "#000000");
                TD.SetAttribute("transparent", "true");
                TD.SetAttribute("leftBorder", "1");
                TD.SetAttribute("topBorder", "1");
                TD.SetAttribute("leftBorderColor", "#808080");
                TD.SetAttribute("leftBorderStyle", "solid");
                TD.SetAttribute("topBorderColor", "#808080");
                TD.SetAttribute("topBorderStyle", "solid");
                TD.SetAttribute("decimal", "2");
                TD.SetAttribute("align", "center");
                TD.SetAttribute("vAlign", "middle");
                TD.SetAttribute("isProtected", "false");
                TD.SetAttribute("isThousandSeparat", "true");
                TD.SetAttribute("isRound", "true");
                TD.SetAttribute("isPrint", "true");
                TD.SetAttribute("font-size", "9");
                DefaultTD.AppendChild(TD);
                Properties.AppendChild(DefaultTD);
                #endregion

                #region [Other]
                XmlElement Other = doc.CreateElement("Other");
                Other.SetAttribute("isShowZero", "true");
                Other.SetAttribute("isRefOriPrecision", "true");
                Other.SetAttribute("LineDistance", "0");
                Other.SetAttribute("isRowHeightAutoExtendAble", "true");
                Properties.AppendChild(Other);
                #endregion

                #region [Fonts]
                XmlElement Fonts = doc.CreateElement("Fonts");
                XmlElement Font  = doc.CreateElement("Font");
                Font.SetAttribute("faceName", "Verdana");
                Font.SetAttribute("height", "-10");
                Font.SetAttribute("weight", "700");
                Fonts.AppendChild(Font);

                Font = doc.CreateElement("Font");
                Font.SetAttribute("faceName", "Verdana");
                Font.SetAttribute("height", "-13");
                Font.SetAttribute("weight", "400");
                Fonts.AppendChild(Font);

                Font = doc.CreateElement("Font");
                Font.SetAttribute("faceName", "楷体");
                Font.SetAttribute("charSet", "134");
                Font.SetAttribute("height", "-27");
                Font.SetAttribute("weight", "700");
                Fonts.AppendChild(Font);

                Font = doc.CreateElement("Font");
                Font.SetAttribute("faceName", "Verdana");
                Font.SetAttribute("height", "-9");
                Font.SetAttribute("weight", "400");
                Fonts.AppendChild(Font);
                WorkSheet.AppendChild(Fonts);
                #endregion

                #region [Table]
                XmlElement Table = doc.CreateElement("Table");
                WorkSheet.AppendChild(Table);

                #region [全局列宽]
                XmlElement Public_Col;
                if (_addReserved)
                {
                    //前预制列
                    Public_Col = doc.CreateElement("Col");
                    Public_Col.SetAttribute("width", "15");
                    Table.AppendChild(Public_Col);
                }
                int tmp_width = 70;
                #region [动态数据列]
                for (int i = 0; i < columns.Rows.Count; i++)
                {
                    Public_Col = doc.CreateElement("Col");
                    Public_Col.SetAttribute("width", tmp_width.ToString());
                    Table.AppendChild(Public_Col);
                }
                #endregion
                //后预制列
                Public_Col = doc.CreateElement("Col");
                Public_Col.SetAttribute("width", "15");
                Table.AppendChild(Public_Col);
                #endregion

                #region [行集合]

                #region [标题行]
                XmlElement Title_TR = doc.CreateElement("TR");
                Title_TR.SetAttribute("height", "45");
                Title_TR.SetAttribute("sequence", "0");
                Table.AppendChild(Title_TR);
                execount++;
                XmlElement Title_TD;
                colid = 0;
                if (_addReserved)
                {
                    //前预制列
                    Title_TD = doc.CreateElement("TD");
                    Title_TD.SetAttribute("col", colid.ToString());
                    Title_TD.SetAttribute("topBorder", "0");
                    Title_TD.SetAttribute("leftBorder", "0");
                    Title_TR.AppendChild(Title_TD);
                    colid++;
                }
                #region [动态生成列]
                for (int i = 0; i < columns.Rows.Count; i++)
                {
                    Title_TD = doc.CreateElement("TD");
                    Title_TD.SetAttribute("col", colid.ToString());
                    Title_TD.SetAttribute("fontIndex", "2");
                    Title_TD.SetAttribute("topBorder", "0");
                    Title_TD.SetAttribute("leftBorder", "0");
                    Title_TD.SetAttribute("align", "center");
                    colid++;
                    if (i == 0)
                    {
                        Title_TD.InnerText = _title;
                        Title_TD.SetAttribute("alias", "Title");
                    }
                    Title_TR.AppendChild(Title_TD);
                }
                #endregion
                //后预制列
                Title_TD = doc.CreateElement("TD");
                Title_TD.SetAttribute("col", colid.ToString());
                Title_TD.SetAttribute("topBorder", "0");
                Title_TD.SetAttribute("leftBorder", "0");
                Title_TR.AppendChild(Title_TD);

                #endregion

                #region [打印时间行]
                XmlElement PrintTime_TR = doc.CreateElement("TR");
                PrintTime_TR.SetAttribute("height", "20");
                PrintTime_TR.SetAttribute("sequence", "0");
                Table.AppendChild(PrintTime_TR);
                execount++;
                //前预制列
                XmlElement PrintTime_TD;
                colid = 0;
                if (_addReserved)
                {
                    PrintTime_TD = doc.CreateElement("TD");
                    PrintTime_TD.SetAttribute("col", colid.ToString());
                    PrintTime_TD.SetAttribute("topBorder", "0");
                    PrintTime_TD.SetAttribute("leftBorder", "0");
                    PrintTime_TR.AppendChild(PrintTime_TD);
                    colid++;
                }
                #region [动态生成列]
                for (int i = 0; i < columns.Rows.Count; i++)
                {
                    PrintTime_TD = doc.CreateElement("TD");
                    PrintTime_TD.SetAttribute("col", colid.ToString());
                    PrintTime_TD.SetAttribute("fontIndex", "1");
                    PrintTime_TD.SetAttribute("topBorder", "0");
                    PrintTime_TD.SetAttribute("leftBorder", "0");
                    colid++;
                    if (i == 0)
                    {
                        PrintTime_TD.SetAttribute("align", "left");
                        PrintTime_TD.SetAttribute("tabOrder", "1");
                        PrintTime_TD.SetAttribute("datatype", "1");
                        //PrintTime_TD.SetAttribute("maskid", "1");
                        //PrintTime_TD.SetAttribute("tip", "选择数据日期,可以查询");
                        PrintTime_TD.SetAttribute("alias", "BeginDate");
                    }
                    else if (i == (columns.Rows.Count - 4))
                    {
                        PrintTime_TD.SetAttribute("tabOrder", "1");
                        PrintTime_TD.SetAttribute("datatype", "1");
                        PrintTime_TD.SetAttribute("align", "right");
                        PrintTime_TD.SetAttribute("alias", "PrintDate");
                        PrintTime_TD.SetAttribute("formula", "=formatDate(now(),'打印时间:YYYY-MM-dd HH:mm:ss')");
                    }
                    PrintTime_TR.AppendChild(PrintTime_TD);
                }
                #endregion
                //后预制列
                PrintTime_TD = doc.CreateElement("TD");
                PrintTime_TD.SetAttribute("col", colid.ToString());
                PrintTime_TD.SetAttribute("topBorder", "0");
                PrintTime_TD.SetAttribute("leftBorder", "0");
                PrintTime_TR.AppendChild(PrintTime_TD);
                #endregion

                #region [字段行]
                XmlElement Column_TR = doc.CreateElement("TR");
                Column_TR.SetAttribute("height", "30");
                Column_TR.SetAttribute("sequence", "0");
                Table.AppendChild(Column_TR);
                execount++;
                //前预制列
                XmlElement Column_TD;
                colid = 0;
                if (_addReserved)
                {
                    Column_TD = doc.CreateElement("TD");
                    Column_TD.SetAttribute("col", colid.ToString());
                    Column_TD.SetAttribute("topBorder", "0");
                    Column_TD.SetAttribute("leftBorder", "0");
                    Column_TR.AppendChild(Column_TD);
                    colid++;
                }
                #region [动态生成列]
                for (int j = 0; j < columns.Rows.Count; j++)
                {
                    Column_TD = doc.CreateElement("TD");
                    Column_TD.SetAttribute("col", colid.ToString());
                    Column_TD.SetAttribute("fontIndex", "1");
                    Column_TD.SetAttribute("align", "center");
                    Column_TD.SetAttribute("decimal", "2");
                    Column_TD.InnerText = columns.Rows[j]["text"].ToString();
                    if (j == 0)
                    {
                        Column_TD.SetAttribute("formula", "=headrow('ds1')");
                        Column_TR.AppendChild(Column_TD);
                    }
                    else
                    {
                        Column_TR.AppendChild(Column_TD);
                    }
                    colid++;
                }
                #endregion
                //后预制列
                Column_TD = doc.CreateElement("TD");
                Column_TD.SetAttribute("col", colid.ToString());
                Column_TD.SetAttribute("topBorder", "0");
                Column_TD.SetAttribute("leftBorder", "1");
                Column_TR.AppendChild(Column_TD);
                #endregion

                #region [数据行]
                XmlElement Data_TR = doc.CreateElement("TR");
                Data_TR.SetAttribute("height", "30");
                Data_TR.SetAttribute("sequence", "0");
                Table.AppendChild(Data_TR);
                execount++;
                XmlElement Data_TD;
                colid = 0;
                if (_addReserved)
                {
                    //前预制列
                    Data_TD = doc.CreateElement("TD");
                    Data_TD.SetAttribute("col", colid.ToString());
                    Data_TD.SetAttribute("topBorder", "0");
                    Data_TD.SetAttribute("leftBorder", "0");
                    Data_TR.AppendChild(Data_TD);
                    colid++;
                }
                #region [动态生成列]
                for (int j = 0; j < columns.Rows.Count; j++)
                {
                    Data_TD = doc.CreateElement("TD");
                    Data_TD.SetAttribute("col", colid.ToString());
                    Data_TD.SetAttribute("fontIndex", "1");
                    Data_TD.SetAttribute("tabOrder", "1");
                    //Data_TD.SetAttribute("datatype", "1");
                    Data_TD.SetAttribute("decimal", "2");
                    //Data_TD.SetAttribute("isRound", "true");
                    Data_TD.SetAttribute("align", "center");
                    //Data_TD.SetAttribute("tip",columns[j].ColumnName);
                    if (j == 0)
                    {
                        Data_TD.SetAttribute("formula", "=datarow('ds1')");
                    }
                    Data_TR.AppendChild(Data_TD);
                    colid++;
                }
                #endregion
                //后预制列
                Data_TD = doc.CreateElement("TD");
                Data_TD.SetAttribute("col", colid.ToString());
                Data_TD.SetAttribute("topBorder", "0");
                Data_TD.SetAttribute("leftBorder", "1");
                Data_TR.AppendChild(Data_TD);
                #endregion

                #region [签字行]
                XmlElement Signature_TR = doc.CreateElement("TR");
                Signature_TR.SetAttribute("height", "30");
                Signature_TR.SetAttribute("sequence", "0");
                Table.AppendChild(Signature_TR);
                //execount++;//签字行后可不累计,因为下文中不再使用
                XmlElement Signature_TD;
                colid = 0;
                if (_addReserved)
                {
                    //前预制列
                    Signature_TD = doc.CreateElement("TD");
                    //Signature_TD.SetAttribute("col", colid.ToString());
                    Signature_TD.SetAttribute("topBorder", "0");
                    Signature_TD.SetAttribute("leftBorder", "0");
                    Signature_TR.AppendChild(Signature_TD);
                    colid++;
                }
                #region [动态生成列]
                for (int i = 0; i < columns.Rows.Count; i++)
                {
                    Signature_TD = doc.CreateElement("TD");
                    //Signature_TD.SetAttribute("col", colid.ToString());
                    Signature_TD.SetAttribute("fontIndex", "1");
                    Signature_TD.SetAttribute("topBorder", "1");
                    Signature_TD.SetAttribute("leftBorder", "0");
                    //Signature_TD.SetAttribute("datatype", "1");
                    //Signature_TD.SetAttribute("tabOrder", "1");
                    Signature_TD.SetAttribute("align", "left");
                    colid++;
                    Signature_TR.AppendChild(Signature_TD);
                }
                #endregion
                //后预制列
                Signature_TD = doc.CreateElement("TD");
                //Signature_TD.SetAttribute("col", colid.ToString());
                Signature_TD.SetAttribute("topBorder", "0");
                Signature_TD.SetAttribute("leftBorder", "0");
                Signature_TR.AppendChild(Signature_TD);
                #endregion

                #endregion

                #endregion

                #region [Merges]
                XmlElement Merges = doc.CreateElement("Merges");
                WorkSheet.AppendChild(Merges);
                #region [标题行合并]
                XmlElement Range = doc.CreateElement("Range");
                Range.SetAttribute("row1", "0");
                Range.SetAttribute("col1", startid.ToString());
                Range.SetAttribute("row2", "0");
                Range.SetAttribute("col2", (colid - 1).ToString());
                Merges.AppendChild(Range);
                #endregion

                #region [打印时间行合并]

                #region [合并时间显示单元格]
                Range = doc.CreateElement("Range");
                Range.SetAttribute("row1", "1");
                Range.SetAttribute("col1", startid.ToString());
                Range.SetAttribute("row2", "1");
                Range.SetAttribute("col2", (startid + 2).ToString());
                Merges.AppendChild(Range);
                #endregion

                #region [合并打印时间单元格]
                Range = doc.CreateElement("Range");
                Range.SetAttribute("row1", "1");
                Range.SetAttribute("col1", (columns.Rows.Count + startid - 4).ToString());
                Range.SetAttribute("row2", "1");
                Range.SetAttribute("col2", (columns.Rows.Count + startid - 1).ToString());
                Merges.AppendChild(Range);
                #endregion
                #endregion

                #region [签字行合并]
                //Range = doc.CreateElement("Range");
                //Range.SetAttribute("row1", execount.ToString());
                //Range.SetAttribute("col1", startid.ToString());
                //Range.SetAttribute("row2", execount.ToString());
                //Range.SetAttribute("col2", (columns.Count - startid).ToString());
                //Merges.AppendChild(Range);
                #endregion

                #endregion

                #region [PrintPage]
                XmlElement PrintPage = doc.CreateElement("PrintPage");
                WorkSheet.AppendChild(PrintPage);

                XmlElement Paper = doc.CreateElement("Paper");
                PrintPage.AppendChild(Paper);

                XmlElement Margin = doc.CreateElement("Margin");
                Other.SetAttribute("left", _pageLeft.ToString());
                Other.SetAttribute("top", _pageTop.ToString());
                Other.SetAttribute("right", _pageRight.ToString());
                Other.SetAttribute("bottom", _pageBottom.ToString());
                Paper.AppendChild(Margin);

                XmlElement Page = doc.CreateElement("Page");
                Page.SetAttribute("align", "center");
                PrintPage.AppendChild(Page);

                XmlElement PageCode = doc.CreateElement("PageCode");
                Page.AppendChild(PageCode);

                XmlElement Page_Font = doc.CreateElement("Font");
                Page_Font.SetAttribute("faceName", "宋体");
                Page_Font.SetAttribute("charSet", "134");
                Page_Font.SetAttribute("height", "-14");
                Page_Font.SetAttribute("weight", "400");
                PageCode.AppendChild(Page_Font);
                #endregion

                #endregion

                #region [DataSources]
                XmlElement DataSources = doc.CreateElement("DataSources");
                DataSources.SetAttribute("Version", "255");
                DataSources.SetAttribute("isAutoCalculateWhenOpen", "false");
                DataSources.SetAttribute("isSaveCalculateResult", "false");
                Report.AppendChild(DataSources);

                #region [DataSource]
                XmlElement DataSource = doc.CreateElement("DataSource");
                DataSource.SetAttribute("type", "4");
                DataSources.AppendChild(DataSource);

                #region [Data]
                XmlElement DS_Data = doc.CreateElement("Data");
                DataSource.AppendChild(DS_Data);

                #region [其他]
                XmlElement DS_ID = doc.CreateElement("ID");
                DS_ID.InnerText = "ds1";
                DS_Data.AppendChild(DS_ID);

                XmlElement DS_Version = doc.CreateElement("Version");
                DS_Version.InnerText = "2";
                DS_Data.AppendChild(DS_Version);

                XmlElement DS_Type = doc.CreateElement("Type");
                DS_Type.InnerText = "4";
                DS_Data.AppendChild(DS_Type);

                XmlElement DS_TypeMeaning = doc.CreateElement("TypeMeaning");
                DS_TypeMeaning.InnerText = "JSON";
                DS_Data.AppendChild(DS_TypeMeaning);

                XmlElement DS_Source = doc.CreateElement("Source");
                DS_Data.AppendChild(DS_Source);

                XmlElement DS_XML_RecordAble_Nodes = doc.CreateElement("XML_RecordAble_Nodes");
                DS_Data.AppendChild(DS_XML_RecordAble_Nodes);
                XmlElement DS_Node = doc.CreateElement("Node");
                DS_XML_RecordAble_Nodes.AppendChild(DS_Node);
                XmlElement DS_name = doc.CreateElement("name");
                DS_Node.AppendChild(DS_name);
                #endregion

                #region [DS_Columns]
                XmlElement DS_Columns = doc.CreateElement("Columns");
                DS_Data.AppendChild(DS_Columns);

                #region [动态生成]
                for (int i = 0; i < columns.Rows.Count; i++)
                {
                    XmlElement DS_Column = doc.CreateElement("Column");
                    DS_Columns.AppendChild(DS_Column);

                    XmlElement Column_name = doc.CreateElement("name");
                    Column_name.InnerText = columns.Rows[i]["name"].ToString();
                    DS_Column.AppendChild(Column_name);

                    XmlElement Column_text = doc.CreateElement("text");
                    Column_text.InnerText = columns.Rows[i]["text"].ToString();
                    DS_Column.AppendChild(Column_text);

                    XmlElement Column_type = doc.CreateElement("type");
                    Column_type.InnerText = columns.Rows[i]["type"].ToString();
                    DS_Column.AppendChild(Column_type);

                    XmlElement Column_visible = doc.CreateElement("visible");
                    Column_visible.InnerText = "true";
                    DS_Column.AppendChild(Column_visible);

                    XmlElement Column_sequence = doc.CreateElement("sequence");
                    Column_sequence.InnerText = (i + 1).ToString();
                    DS_Column.AppendChild(Column_sequence);
                }

                #endregion

                #endregion

                #endregion

                #endregion

                #endregion

                #region [保存XML到文件]
                if (_savePath != "" && _savePath != null)
                {
                    doc.Save(_savePath);
                }
                return(true);

                #endregion
            }
            catch
            {
                return(false);
            }
        }
コード例 #9
0
ファイル: XmlNodeConverter.cs プロジェクト: zhouweiaccp/sones
        private void SerializeNode(JsonWriter writer, XmlNode node, bool writePropertyName)
        {
            switch (node.NodeType)
            {
            case XmlNodeType.Document:
            case XmlNodeType.DocumentFragment:
                SerializeGroupedNodes(writer, node);
                break;

            case XmlNodeType.Element:
                if (writePropertyName)
                {
                    writer.WritePropertyName(node.Name);
                }

                if (ValueAttributes(node.Attributes).Count() == 0 && node.ChildNodes.Count == 1 &&
                    node.ChildNodes[0].NodeType == XmlNodeType.Text)
                {
                    // write elements with a single text child as a name value pair
                    writer.WriteValue(node.ChildNodes[0].Value);
                }
                else if (node.ChildNodes.Count == 0 && CollectionUtils.IsNullOrEmpty(node.Attributes))
                {
                    // empty element
                    writer.WriteNull();
                }
                else if (node.ChildNodes.OfType <XmlElement>().Where(x => x.Name.StartsWith("-")).Count() > 1)
                {
                    XmlElement constructorValueElement = node.ChildNodes.OfType <XmlElement>().Where(x => x.Name.StartsWith("-")).First();
                    string     constructorName         = constructorValueElement.Name.Substring(1);

                    writer.WriteStartConstructor(constructorName);

                    for (int i = 0; i < node.ChildNodes.Count; i++)
                    {
                        SerializeNode(writer, node.ChildNodes[i], false);
                    }

                    writer.WriteEndConstructor();
                }
                else
                {
                    writer.WriteStartObject();

                    for (int i = 0; i < node.Attributes.Count; i++)
                    {
                        SerializeNode(writer, node.Attributes[i], true);
                    }

                    SerializeGroupedNodes(writer, node);

                    writer.WriteEndObject();
                }

                break;

            case XmlNodeType.Comment:
                if (writePropertyName)
                {
                    writer.WriteComment(node.Value);
                }
                break;

            case XmlNodeType.Attribute:
            case XmlNodeType.Text:
            case XmlNodeType.CDATA:
            case XmlNodeType.ProcessingInstruction:
            case XmlNodeType.Whitespace:
            case XmlNodeType.SignificantWhitespace:
                if (node.Prefix == "xmlns" && node.Value == JsonNamespaceUri)
                {
                    break;
                }
                else if (node.NamespaceURI == JsonNamespaceUri)
                {
                    break;
                }

                if (writePropertyName)
                {
                    writer.WritePropertyName(GetPropertyName(node));
                }
                writer.WriteValue(node.Value);
                break;

            case XmlNodeType.XmlDeclaration:
                XmlDeclaration declaration = (XmlDeclaration)node;
                writer.WritePropertyName(GetPropertyName(node));
                writer.WriteStartObject();

                if (!string.IsNullOrEmpty(declaration.Version))
                {
                    writer.WritePropertyName("@version");
                    writer.WriteValue(declaration.Version);
                }
                if (!string.IsNullOrEmpty(declaration.Encoding))
                {
                    writer.WritePropertyName("@encoding");
                    writer.WriteValue(declaration.Encoding);
                }
                if (!string.IsNullOrEmpty(declaration.Standalone))
                {
                    writer.WritePropertyName("@standalone");
                    writer.WriteValue(declaration.Standalone);
                }

                writer.WriteEndObject();
                break;

            default:
                throw new JsonSerializationException("Unexpected XmlNodeType when serializing nodes: " + node.NodeType);
            }
        }
コード例 #10
0
ファイル: Export.cs プロジェクト: pheijmans-zz/GAPP
        protected override void ExportMethod()
        {
            try
            {
                using (Utils.ProgressBlock progress = new Utils.ProgressBlock(this, STR_EXPORTINGGPX, STR_CREATINGFILE, _gcList.Count, 0, true))
                {
                    bool cancel = false;
                    _indexDone = 0;

                    if (File.Exists(_filename))
                    {
                        File.Delete(_filename);
                    }

                    //create temp folder / delete files
                    string tempFolder    = System.IO.Path.Combine(Core.PluginDataPath, "KmlExport");
                    string tempImgFolder = System.IO.Path.Combine(tempFolder, "Images");
                    if (!Directory.Exists(tempFolder))
                    {
                        Directory.CreateDirectory(tempFolder);
                    }
                    else
                    {
                        string[] fls = Directory.GetFiles(tempFolder);
                        if (fls != null && fls.Length > 0)
                        {
                            foreach (string s in fls)
                            {
                                File.Delete(s);
                            }
                        }
                    }
                    if (!Directory.Exists(tempImgFolder))
                    {
                        Directory.CreateDirectory(tempImgFolder);
                    }
                    else
                    {
                        string[] fls = Directory.GetFiles(tempImgFolder);
                        if (fls != null && fls.Length > 0)
                        {
                            foreach (string s in fls)
                            {
                                File.Delete(s);
                            }
                        }
                    }

                    XmlDocument    doc = new XmlDocument();
                    XmlDeclaration pi  = doc.CreateXmlDeclaration("1.0", "utf-8", "yes");
                    doc.InsertBefore(pi, doc.DocumentElement);
                    XmlElement root = doc.CreateElement("kml");
                    doc.AppendChild(root);
                    XmlAttribute attr = doc.CreateAttribute("creator");
                    XmlText      txt  = doc.CreateTextNode("GAPP, Globalcaching Application");
                    attr.AppendChild(txt);
                    root.Attributes.Append(attr);
                    attr = doc.CreateAttribute("xmlns");
                    txt  = doc.CreateTextNode("http://www.opengis.net/kml/2.2");
                    attr.AppendChild(txt);
                    root.Attributes.Append(attr);

                    XmlElement rootDoc = doc.CreateElement("Document");
                    root.AppendChild(rootDoc);

                    XmlElement el = doc.CreateElement("name");
                    txt = doc.CreateTextNode(Path.GetFileNameWithoutExtension(_filename));
                    el.AppendChild(txt);
                    rootDoc.AppendChild(el);

                    List <Framework.Data.GeocacheType> typeList = new List <Framework.Data.GeocacheType>();
                    List <Framework.Data.Geocache>     gs;
                    List <string> fileList = new List <string>();
                    foreach (Framework.Data.GeocacheType gt in Core.GeocacheTypes)
                    {
                        gs = (from g in _gcList where g.GeocacheType == gt && !g.Found && !g.IsOwn select g).ToList();
                        if (gs.Count > 0)
                        {
                            if (!addGeocaches(progress, gs, typeList, doc, rootDoc, Utils.LanguageSupport.Instance.GetTranslation(gt.Name), tempImgFolder, fileList))
                            {
                                cancel = true;
                                break;
                            }
                        }
                    }
                    gs = (from g in _gcList where g.Found select g).ToList();
                    if (!cancel && gs.Count > 0)
                    {
                        if (!addGeocaches(progress, gs, typeList, doc, rootDoc, Utils.LanguageSupport.Instance.GetTranslation(STR_FOUND), tempImgFolder, fileList))
                        {
                            cancel = true;
                        }
                    }

                    gs = (from g in _gcList where g.IsOwn select g).ToList();
                    if (!cancel && gs.Count > 0)
                    {
                        if (!addGeocaches(progress, gs, typeList, doc, rootDoc, Utils.LanguageSupport.Instance.GetTranslation(STR_YOURS), tempImgFolder, fileList))
                        {
                            cancel = true;
                        }
                    }

                    if (!cancel)
                    {
                        string kmlFilename = System.IO.Path.Combine(tempFolder, "doc.kml");
                        using (TextWriter sw = new StreamWriter(kmlFilename, false, Encoding.UTF8)) //Set encoding
                        {
                            doc.Save(sw);
                        }
                        fileList.Add(kmlFilename);

                        using (ZipOutputStream s = new ZipOutputStream(System.IO.File.Create(_filename)))
                        {
                            s.SetLevel(9); // 0-9, 9 being the highest compression

                            byte[] buffer = new byte[4096];
                            fileList.Reverse();
                            foreach (string file in fileList)
                            {
                                ZipEntry entry = new ZipEntry(System.IO.Path.GetFileName(file) == "doc.kml" ? System.IO.Path.GetFileName(file) : string.Format("Images/{0}", System.IO.Path.GetFileName(file)));

                                entry.DateTime = DateTime.Now;
                                FileInfo fi = new FileInfo(file);
                                entry.Size = fi.Length;
                                s.PutNextEntry(entry);

                                using (System.IO.FileStream fs = System.IO.File.OpenRead(file))
                                {
                                    int sourceBytes;
                                    do
                                    {
                                        sourceBytes = fs.Read(buffer, 0, buffer.Length);
                                        s.Write(buffer, 0, sourceBytes);
                                    } while (sourceBytes > 0);
                                }
                            }
                            s.Finish();
                            s.Close();
                        }
                    }
                }
            }
            catch (Exception e)
            {
                System.Windows.Forms.MessageBox.Show(e.Message, Utils.LanguageSupport.Instance.GetTranslation(STR_ERROR));
            }
        }
コード例 #11
0
        static void Main(string[] args)
        {
            /*
             * Linq to xml   xdoument, Xelement ,XAttribute
             */
            #region xdocumnt linq to xml => navighi ,crei , edito

            //creation

            //v0

            XDocument docx = new XDocument(new XElement("body",
                                                        new XElement("level1",
                                                                     new XElement("level2", "text"),
                                                                     new XElement("level2", "other text"))));
            docx.Save("testx0.xml");

            //v1
            XDocument srcTree = new XDocument(
                new XComment("This is a comment"),
                new XElement("Root",
                             new XElement("Child1", "data1"),
                             new XElement("Child2", "data2"),
                             new XElement("Child3", "data3"),
                             new XElement("Child2", "data4"),
                             new XElement("Info5", "info5"),
                             new XElement("Info6", "info6"),
                             new XElement("Info7", "info7"),
                             new XElement("Info8", "info8")
                             )
                //,new XAttribute("MyAtt",42)
                );
            srcTree.Save("testx1.xml");

            //v2
            XDocument xmlDocument = new XDocument(
                new XDeclaration("1.0", "utf-8", "yes"),

                new XComment("Creating an XML Tree using LINQ to XML"),

                new XElement("Students",

                             from student in Student.GetAllStudents()
                             select new XElement("Student", new XAttribute("Id", student.Id),
                                                 new XElement("Name", student.Name),
                                                 new XElement("Gender", student.Gender),
                                                 new XElement("TotalMarks", student.TotalMarks))
                             ));

            xmlDocument.Save(@"testx2.xml");


            //add
            XDocument xmlDocument2 = XDocument.Load(@"testx2.xml");

            xmlDocument2.Element("Students").Add(
                new XElement("Student", new XAttribute("Id", 105),
                             new XElement("Name", "Todd"),
                             new XElement("Gender", "Male"),
                             new XElement("TotalMarks", 980)
                             ));

            xmlDocument2.Save(@"testx2.xml");


            xmlDocument2.Element("Students")
            .Elements("Student")
            .Where(x => x.Attribute("Id").Value == "103").FirstOrDefault()
            .AddBeforeSelf(
                new XElement("Student", new XAttribute("Id", 106),
                             new XElement("Name", "Todd"),
                             new XElement("Gender", "Male"),
                             new XElement("TotalMarks", 980)));


            //update
            XDocument xmlDocument3 = XDocument.Load(@"testx2.xml");

            xmlDocument3.Element("Students")
            .Elements("Student")
            .Where(x => x.Attribute("Id").Value == "105").FirstOrDefault()
            .SetElementValue("TotalMarks", 999);

            xmlDocument3.Save(@"testx2.xml");

            XDocument xmlDocumen4 = XDocument.Load(@"testx2.xml");

            xmlDocumen4.Element("Students")
            .Elements("Student")
            .Where(x => x.Attribute("Id").Value == "105")
            .Select(x => x.Element("TotalMarks")).FirstOrDefault().SetValue(999);

            xmlDocumen4.Save(@"testx2.xml");


            //query
            IEnumerable <string> names = from student in XDocument
                                         .Load(@"testx2.xml")
                                         .Descendants("Student")
                                         where (int)student.Element("TotalMarks") > 800
                                         orderby(int) student.Element("TotalMarks") descending
                                         select student.Element("Name").Value;

            foreach (string name in names)
            {
                Console.WriteLine(name);
            }
            #endregion

            /*
             * meno performante   xmldocument , xmldocument ,  XmlElement
             * read the whole thing into memory and build a DOM
             */
            #region xmldocumnt => navighi , crei, edito


            //v0
            XmlDocument doc2 = new XmlDocument();

            //(1) the xml declaration is recommended, but not mandatory
            XmlDeclaration xmlDeclaration = doc2.CreateXmlDeclaration("1.0", "UTF-8", null);
            XmlElement     root           = doc2.DocumentElement;
            doc2.InsertBefore(xmlDeclaration, root);

            //(2) string.Empty makes cleaner code
            XmlElement element1 = doc2.CreateElement(string.Empty, "body", string.Empty);
            doc2.AppendChild(element1);

            XmlElement element2 = doc2.CreateElement(string.Empty, "level1", string.Empty);
            element1.AppendChild(element2);

            XmlElement element3 = doc2.CreateElement(string.Empty, "level2", string.Empty);
            XmlText    text1    = doc2.CreateTextNode("text");
            element3.AppendChild(text1);
            element2.AppendChild(element3);

            XmlElement element4 = doc2.CreateElement(string.Empty, "level2", string.Empty);
            XmlText    text2    = doc2.CreateTextNode("other text");
            element4.AppendChild(text2);
            element2.AppendChild(element4);

            doc2.Save(@"testxmldocument.xml");


            //v1
            XmlDocument doc = new XmlDocument();
            doc.Load("testxml.xml");

            XmlNodeList nodeList;
            XmlNode     root1 = doc.DocumentElement;

            nodeList = doc.GetElementsByTagName("Person", "");

            //Change the price on the books.
            foreach (XmlNode node in nodeList)
            {
                var first = node.Attributes["firstname"].Value;
                Console.WriteLine(first);
                if (root1.HasChildNodes)
                {
                    for (int i = 0; i < root1.ChildNodes.Count; i++)
                    {
                        Console.WriteLine(root1.ChildNodes[i].InnerText);
                    }
                }
            }
            XmlElement bookElement = (XmlElement)nodeList[1];

            // Get the attributes of a book.
            bookElement.SetAttribute("firstname", "ricky");

            // Get the values of child elements of a book.
            //bookElement["EmailAddress"].InnerText = "antani@sblinda";

            //Creo
            XmlNode      newnode    = doc.CreateNode(XmlNodeType.Element, "Person", "");
            XmlAttribute fAttribute = doc.CreateAttribute("lastname");
            fAttribute.Value = "izzooo";
            newnode.Attributes.Append(fAttribute);
            doc.DocumentElement.AppendChild(newnode);

            doc.Save(Console.Out);
            #endregion


            /*
             * Fast way create read no cache
             * Rappresenta un writer che fornisce un modo veloce, non in cache e di tipo forward-only
             * per generare flussi o i file contenenti dati XML.
             * XmlReader/Writer are sequential access streams. You will have to read in on one end,
             * process the stream how you want, and write it out the other end. The advantage is that you don't need to read
             * the whole thing into memory and build a DOM, which is what you'd get with any XmlDocument-based approach.
             *
             */
            #region xmlreader =>  crei / navighi xml, NON POSSO EDITARE

            //
            var myreader = XmlReader.Create("products.xml");
            myreader.MoveToContent();
            while (myreader.Read())
            {
                var result = myreader.NodeType;
                //{
                //    XmlNodeType.Element when myreader.Name == "product" => $"{myreader.Name}\n",
                //    XmlNodeType.Element => $"{myreader.Name}: ",
                //    XmlNodeType.Text => $"{myreader.Value}\n",
                //    XmlNodeType.EndElement when myreader.Name == "product" =>  "----------------------\n",
                //    _ => ""
                //};

                Console.Write(result);
            }

            //
            XmlReader readerexample = XmlReader.Create("products.xml");
            readerexample.MoveToContent();

            while (readerexample.MoveToContent() == XmlNodeType.Element && readerexample.LocalName == ChildXmlTag)
            {
                readerexample.ReadStartElement();
                readerexample.MoveToContent();

                //IilParameter p = IilParameter.fromString(readerexample.LocalName);
                //p.ReadXml(readerexample);
                //Parameters.Add(p);
                //readerexample.ReadEndElement();
            }
            readerexample.ReadEndElement();

            //
            XmlReader reader5 = XmlReader.Create("products.xml");
            reader5.MoveToContent();
            var empty = reader5.IsEmptyElement;
            reader5.ReadStartElement();
            if (!empty)
            {
                while (reader5.MoveToContent() == XmlNodeType.Element)
                {
                    //if (reader5.Name == @"ProductName" && !reader5.IsEmptyElement)
                    //{
                    //    ProductName = reader5.ReadElementString();
                    //}
                    //else if (reader5.Name == @"GlyphColor" && !reader5.IsEmptyElement)
                    //{
                    //    GlyphColor = ParseColor(reader5.ReadElementString());
                    //}
                    //else
                    //{
                    //    // consume the bad element and skip to next sibling or the parent end element tag
                    //    reader5.ReadOuterXml();
                    //}
                }
                reader5.MoveToContent();
                reader5.ReadEndElement();
            }



            //MODO0 leggo da uno scrivo da un altro
            using (FileStream readStream = new FileStream(@"xmlreadertest.xml", FileMode.OpenOrCreate, FileAccess.Read, FileShare.Write))
            {
                using (FileStream writeStream = new FileStream(@"xmlreadertestNEW.xml", FileMode.OpenOrCreate, FileAccess.Write))
                {
                    PostProcess(readStream, writeStream);
                }
            }

            //MODO1
            XmlReader xmlReader = XmlReader.Create("test.xml");
            while (xmlReader.Read())
            {
                if ((xmlReader.NodeType == XmlNodeType.Element) && (xmlReader.Name == "book"))
                {
                    if (xmlReader.HasAttributes)
                    {
                        Console.WriteLine(xmlReader.GetAttribute("genre"));
                    }
                }

                if ((xmlReader.NodeType == XmlNodeType.Element) && (xmlReader.Name == "title"))
                {
                    Console.WriteLine($"title: {xmlReader.ReadElementContentAsString()}");
                }
            }

            //MODO2
            var reader1 = XmlReader.Create("test1.xml");
            reader1.ReadToFollowing("book");

            do
            {
                reader1.MoveToFirstAttribute();
                Console.WriteLine($"genre: {reader1.Value}");

                reader1.ReadToFollowing("title");
                Console.WriteLine($"title: {reader1.ReadElementContentAsString()}");

                reader1.ReadToFollowing("author");
                Console.WriteLine($"author: {reader1.ReadElementContentAsString()}");

                reader1.ReadToFollowing("price");
                Console.WriteLine($"price: {reader1.ReadElementContentAsString()}");

                Console.WriteLine("-------------------------");
            } while (reader1.ReadToFollowing("book"));


            //MODO3
            using (XmlReader readertest = XmlReader.Create("test3.xml"))
            {
                while (readertest.Read())
                {
                    // Only detect start elements.
                    if (readertest.IsStartElement())
                    {
                        // Get element name and switch on it.
                        switch (readertest.Name)
                        {
                        case "perls":
                            // Detect this element.
                            Console.WriteLine("Start <perls> element.");
                            break;

                        case "article":
                            // Detect this article element.
                            Console.WriteLine("Start <article> element.");
                            // Search for the attribute name on this current node.
                            string attribute = readertest["name"];
                            if (attribute != null)
                            {
                                Console.WriteLine("  Has attribute name: " + attribute);
                            }
                            // Next read will contain text.
                            if (readertest.Read())
                            {
                                Console.WriteLine("  Text node: " + readertest.Value.Trim());
                            }
                            break;
                        } //fine switch
                    }     //fine if
                }
            }

            #endregion
        }
コード例 #12
0
        /**
         * Writes the daventure data into the given file.
         *
         * @param folderName
         *            Folder where to write the data
         * @param adventureData
         *            Adventure data to write in the file
         * @param valid
         *            True if the adventure is valid (can be executed in the
         *            engine), false otherwise
         * @return True if the operation was succesfully completed, false otherwise
         */

        public static bool writeData(string folderName, AdventureDataControl adventureData, bool valid)
        {
            bool dataSaved = false;

            // Create the necessary elements for building the DOM
            doc = new XmlDocument();

            // Delete the previous XML files in the root of the project dir
            //DirectoryInfo projectFolder = new DirectoryInfo(folderName);
            //if (projectFolder.Exists)
            //{
            //    foreach (FileInfo file in projectFolder.GetFiles())
            //    {
            //        file.Delete();
            //    }
            //    foreach (DirectoryInfo dir in projectFolder.GetDirectories())
            //    {
            //        dir.Delete(true);
            //    }
            //}

            // Add the special asset files
            // TODO AssetsController.addSpecialAssets();

            /** ******* START WRITING THE DESCRIPTOR ********* */
            // Pick the main node for the descriptor
            XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "UTF-8", "no");

            //XmlDocumentType typeDescriptor = doc.CreateDocumentType("game-descriptor", "SYSTEM", "descriptor.dtd", null);
            doc.AppendChild(declaration);
            //doc.AppendChild(typeDescriptor);

            if (!valid)
            {
                DOMWriterUtility.DOMWrite(doc, adventureData, new DescriptorDOMWriter.InvalidAdventureDataControlParam());
            }
            else
            {
                DOMWriterUtility.DOMWrite(doc, adventureData);
            }

            doc.Save(folderName + "/descriptor.xml");
            /** ******** END WRITING THE DESCRIPTOR ********** */

            /** ******* START WRITING THE CHAPTERS ********* */
            // Write every chapter
            //XmlDocumentType typeChapter;

            int chapterIndex = 1;

            foreach (Chapter chapter in adventureData.getChapters())
            {
                doc         = new XmlDocument();
                declaration = doc.CreateXmlDeclaration("1.0", "UTF-8", "no");
                //typeChapter = doc.CreateDocumentType("eAdventure", "SYSTEM", "eadventure.dtd", null);
                doc.AppendChild(declaration);
                //doc.AppendChild(typeChapter);

                DOMWriterUtility.DOMWrite(doc, chapter);

                doc.Save(folderName + "/chapter" + chapterIndex++ + ".xml");
            }
            /** ******** END WRITING THE CHAPTERS ********** */
            dataSaved = true;
            return(dataSaved);
        }
コード例 #13
0
ファイル: FiapXml.cs プロジェクト: rascmisc/SoapTest
        public void MakeFiapMessage(string keyid, string LBtime, string UBtime)
        {
            StringWriterUTF8 writer   = new StringWriterUTF8();
            XmlDocument      document = new XmlDocument();

            try
            {
                XmlDeclaration declaration = document.CreateXmlDeclaration("1.0", null, null);  // XML宣言
                document.AppendChild(declaration);

                XmlElement root;
                XmlNode    x1, x2, x3, x4, x5, x6;
                root = document.CreateElement("soapenv", "Envelope", "xmlns");
                root.SetAttribute("xmlns:soapenv", "http://schemas.xmlsoap.org/soap/envelope/");
                root.SetAttribute("xmlns:soap", "http://soap.fiap.org/");
                root.SetAttribute("xmlns:ns", "http://gutp.jp/fiap/2009/11/");


                x1 = document.CreateNode(XmlNodeType.Element, "soapenv:Body", "http://schemas.xmlsoap.org/soap/envelope/");
                x2 = document.CreateNode(XmlNodeType.Element, "soap:queryRQ", "http://soap.fiap.org/");
                x3 = document.CreateNode(XmlNodeType.Element, "ns:transport", "http://gutp.jp/fiap/2009/11/");
                x4 = document.CreateNode(XmlNodeType.Element, "ns:header", "http://gutp.jp/fiap/2009/11/");
                x5 = document.CreateNode(XmlNodeType.Element, "ns:query", "http://gutp.jp/fiap/2009/11/");
                XmlAttribute attr;

                attr       = document.CreateAttribute("id");
                attr.Value = "0a90f1fa-bdb4-48ff-87d3-661d2af6ff4c";
                x5.Attributes.SetNamedItem(attr);
                attr       = document.CreateAttribute("type");
                attr.Value = "storage";
                x5.Attributes.SetNamedItem(attr);
                root.AppendChild(x1);
                x1.AppendChild(x2);
                x2.AppendChild(x3);
                x3.AppendChild(x4);
                x4.AppendChild(x5);

                string[] lines = keyid.Split(new string[] { "\r\n" }, StringSplitOptions.None);
                if (LBtime == "")
                {
                    foreach (string line in lines)
                    {
                        x6 = document.CreateNode(XmlNodeType.Element, "ns:key", "http://gutp.jp/fiap/2009/11/");

                        attr       = document.CreateAttribute("id");
                        attr.Value = line;
                        x6.Attributes.SetNamedItem(attr);
                        attr       = document.CreateAttribute("attrName");
                        attr.Value = "time";
                        x6.Attributes.SetNamedItem(attr);
                        attr       = document.CreateAttribute("select");
                        attr.Value = "maximum";
                        x6.Attributes.SetNamedItem(attr);
                        x5.AppendChild(x6);
                    }
                }
                else
                {
                    foreach (string line in lines)
                    {
                        x6 = document.CreateNode(XmlNodeType.Element, "ns:key", "http://gutp.jp/fiap/2009/11/");

                        attr       = document.CreateAttribute("id");
                        attr.Value = line;
                        x6.Attributes.SetNamedItem(attr);
                        attr       = document.CreateAttribute("attrName");
                        attr.Value = "time";
                        x6.Attributes.SetNamedItem(attr);
                        attr       = document.CreateAttribute("lteq");
                        attr.Value = LBtime;
                        x6.Attributes.SetNamedItem(attr);
                        attr       = document.CreateAttribute("gteq");
                        attr.Value = UBtime;
                        x6.Attributes.SetNamedItem(attr);
                        x5.AppendChild(x6);
                    }
                }
                document.AppendChild(root);//xmlDocumentオブジェクトにルートノード追加

                document.Save(writer);
                xml = writer.ToString();
                writer.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                MessageBox.Show(ex.Message);
            }
        }
コード例 #14
0
ファイル: Program.cs プロジェクト: Tiny-Chen/CSharp-Basic
        static void Main(string[] args)
        {
            #region 带属性的写法

            /*
             * //在元素内容中需要添加标签时使用InnerXml,如在内容前面加<p></p>标签
             * //创建XML文档对象
             * XmlDocument doc = new XmlDocument();
             * //创建节点信息
             * XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);
             * doc.AppendChild(dec);
             * //创建根节点
             * XmlElement order = doc.CreateElement("Order");
             * doc.AppendChild(order);
             * //创建子节点1
             * XmlElement customerName = doc.CreateElement("CustomerName");
             * customerName.InnerText = "刘洋";
             * order.AppendChild(customerName);
             * //创建子节点2
             * XmlElement orderNumber = doc.CreateElement("OrderNumber");
             * //在内容前面加<p></p>标签----------InnerXml,如果添加标签使用text的话,会变成转义符
             * orderNumber.InnerXml = "<p>bj0000001</p>";
             * order.AppendChild(orderNumber);
             * //创建子节点3
             * XmlElement items = doc.CreateElement("Items");
             * order.AppendChild(items);
             *
             * //创建子节点3下的属性节点1
             * XmlElement orderItem1 = doc.CreateElement("orderItem");
             * orderItem1.SetAttribute("Name", "码表");
             * orderItem1.SetAttribute("Count", "10");
             * items.AppendChild(orderItem1);
             *
             * XmlElement orderlItem2 = doc.CreateElement("orderItem");
             * orderlItem2.SetAttribute("Name", "雨衣");
             * orderlItem2.SetAttribute("Count", "40");
             * items.AppendChild(orderlItem2);
             *
             * XmlElement orderlItem3 = doc.CreateElement("OrderItem");
             * orderlItem3.SetAttribute("Name", "手套");
             * orderlItem3.SetAttribute("Count", "30");
             * items.AppendChild(orderlItem3);
             * //保存XML文件
             * doc.Save("Preans.xml");
             * Console.WriteLine("保存成功");
             */
            #endregion

            //-----------------------------------------------------------------------------

            //追加XML文档内容
            //建立文档对象
            XmlDocument doc = new XmlDocument();
            //创建根节点
            XmlElement order;
            //判断是否存在文档
            if (File.Exists("Preans.xml"))
            {
                //如果存在,加载XML文件
                doc.Load("Preans.xml");
                //获得根节点
                order = doc.DocumentElement;
            }
            else
            {
                //如果文件不存
                //创建第一行节点信息
                XmlDeclaration xdec = doc.CreateXmlDeclaration("1.0", "utf-8", null);
                //创建根节点
                order = doc.CreateElement("Order");
            }

            //追加内容
            XmlElement customerName = doc.CreateElement("CustomerName");
            customerName.InnerText = "我是追加的内容";
            order.AppendChild(customerName);

            doc.Save("Preans.xml");
            Console.WriteLine("追加成功");
            Console.ReadKey();
        }
コード例 #15
0
        private void DefaultXMLOnClick(object sender, EventArgs e)
        {
            string FileName = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, @"plugins/MassImport.xml");

            XmlDocument    dom  = new XmlDocument();
            XmlDeclaration decl = dom.CreateXmlDeclaration("1.0", "utf-8", null);

            dom.AppendChild(decl);

            XmlComment comment = dom.CreateComment(
                Environment.NewLine + @"MassImport Control XML" + Environment.NewLine +
                @"Supported Nodes: item/landtile/texture/gump/tiledataitem/tiledataland/hue" + Environment.NewLine +
                @"file=relativ or absolute" + Environment.NewLine +
                @"remove=bool" + Environment.NewLine +
                @"Examples:" + Environment.NewLine +
                @"<item index='195' file='test.bmp' remove='False' /> -> Adds/Replace ItemArt from text.bmp to 195" + Environment.NewLine +
                @"<landtile index='195' file='C:\import\test.bmp' remove='False' />-> Adds/Replace LandTileArt from c:\import\text.bmp to 195" + Environment.NewLine +
                @"<gump index='100' file='' remove='True' /> -> Removes gump with index 100" + Environment.NewLine +
                @"<tiledataitem index='100' file='test.csv' remove='False' /> -> Reads TileData information from test.csv for index 100" + Environment.NewLine +
                @"Note: TileData.csv can be one for all (it searches for the right entry)"
                );

            dom.AppendChild(comment);

            XmlElement sr = dom.CreateElement("MassImport");
            XmlElement elem;

            elem = dom.CreateElement("item");
            elem.SetAttribute("index", "195");
            elem.SetAttribute("file", "test.bmp");
            elem.SetAttribute("remove", "False");
            sr.AppendChild(elem);
            elem = dom.CreateElement("item");
            elem.SetAttribute("index", "1");
            elem.SetAttribute("file", "test.bmp");
            elem.SetAttribute("remove", "True");
            sr.AppendChild(elem);

            elem = dom.CreateElement("landtile");
            elem.SetAttribute("index", "0");
            elem.SetAttribute("file", "");
            elem.SetAttribute("remove", "False");
            sr.AppendChild(elem);

            elem = dom.CreateElement("texture");
            elem.SetAttribute("index", "0");
            elem.SetAttribute("file", "");
            elem.SetAttribute("remove", "False");
            sr.AppendChild(elem);

            elem = dom.CreateElement("gump");
            elem.SetAttribute("index", "0");
            elem.SetAttribute("file", "");
            elem.SetAttribute("remove", "False");
            sr.AppendChild(elem);

            elem = dom.CreateElement("tiledataland");
            elem.SetAttribute("index", "0");
            elem.SetAttribute("file", "");
            elem.SetAttribute("remove", "False");
            sr.AppendChild(elem);

            elem = dom.CreateElement("tiledataitem");
            elem.SetAttribute("index", "0");
            elem.SetAttribute("file", "");
            elem.SetAttribute("remove", "False");
            sr.AppendChild(elem);

            elem = dom.CreateElement("hue");
            elem.SetAttribute("index", "0");
            elem.SetAttribute("file", "");
            elem.SetAttribute("remove", "False");
            sr.AppendChild(elem);

            dom.AppendChild(sr);
            dom.Save(FileName);
            MessageBox.Show(String.Format("Default xml saved to {0}", FileName), "Saved", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
        }
コード例 #16
0
ファイル: XmlNodeConverter.cs プロジェクト: zhouweiaccp/sones
        private void DeserializeValue(JsonReader reader, XmlDocument document, XmlNamespaceManager manager, string propertyName, XmlNode currentNode)
        {
            switch (propertyName)
            {
            case TextName:
                currentNode.AppendChild(document.CreateTextNode(reader.Value.ToString()));
                break;

            case CDataName:
                currentNode.AppendChild(document.CreateCDataSection(reader.Value.ToString()));
                break;

            case WhitespaceName:
                currentNode.AppendChild(document.CreateWhitespace(reader.Value.ToString()));
                break;

            case SignificantWhitespaceName:
                currentNode.AppendChild(document.CreateSignificantWhitespace(reader.Value.ToString()));
                break;

            default:
                // processing instructions and the xml declaration start with ?
                if (!string.IsNullOrEmpty(propertyName) && propertyName[0] == '?')
                {
                    if (propertyName == DeclarationName)
                    {
                        string version    = null;
                        string encoding   = null;
                        string standalone = null;
                        while (reader.Read() && reader.TokenType != JsonToken.EndObject)
                        {
                            switch (reader.Value.ToString())
                            {
                            case "@version":
                                reader.Read();
                                version = reader.Value.ToString();
                                break;

                            case "@encoding":
                                reader.Read();
                                encoding = reader.Value.ToString();
                                break;

                            case "@standalone":
                                reader.Read();
                                standalone = reader.Value.ToString();
                                break;

                            default:
                                throw new JsonSerializationException("Unexpected property name encountered while deserializing XmlDeclaration: " + reader.Value);
                            }
                        }

                        XmlDeclaration declaration = document.CreateXmlDeclaration(version, encoding, standalone);
                        currentNode.AppendChild(declaration);
                    }
                    else
                    {
                        XmlProcessingInstruction instruction = document.CreateProcessingInstruction(propertyName.Substring(1), reader.Value.ToString());
                        currentNode.AppendChild(instruction);
                    }
                }
                else
                {
                    // deserialize xml element
                    bool   finishedAttributes = false;
                    bool   finishedElement    = false;
                    string elementPrefix      = GetPrefix(propertyName);
                    Dictionary <string, string> attributeNameValues = new Dictionary <string, string>();

                    if (reader.TokenType == JsonToken.StartArray)
                    {
                        XmlElement nestedArrayElement = CreateElement(propertyName, document, elementPrefix, manager);

                        currentNode.AppendChild(nestedArrayElement);

                        while (reader.Read() && reader.TokenType != JsonToken.EndArray)
                        {
                            DeserializeValue(reader, document, manager, propertyName, nestedArrayElement);
                        }

                        return;
                    }

                    // a string token means the element only has a single text child
                    if (reader.TokenType != JsonToken.String &&
                        reader.TokenType != JsonToken.Null &&
                        reader.TokenType != JsonToken.Boolean &&
                        reader.TokenType != JsonToken.Integer &&
                        reader.TokenType != JsonToken.Float &&
                        reader.TokenType != JsonToken.Date &&
                        reader.TokenType != JsonToken.StartConstructor)
                    {
                        // read properties until first non-attribute is encountered
                        while (!finishedAttributes && !finishedElement && reader.Read())
                        {
                            switch (reader.TokenType)
                            {
                            case JsonToken.PropertyName:
                                string attributeName = reader.Value.ToString();

                                if (attributeName[0] == '@')
                                {
                                    attributeName = attributeName.Substring(1);
                                    reader.Read();
                                    string attributeValue = reader.Value.ToString();
                                    attributeNameValues.Add(attributeName, attributeValue);

                                    string namespacePrefix;

                                    if (IsNamespaceAttribute(attributeName, out namespacePrefix))
                                    {
                                        manager.AddNamespace(namespacePrefix, attributeValue);
                                    }
                                }
                                else
                                {
                                    finishedAttributes = true;
                                }
                                break;

                            case JsonToken.EndObject:
                                finishedElement = true;
                                break;

                            default:
                                throw new JsonSerializationException("Unexpected JsonToken: " + reader.TokenType);
                            }
                        }
                    }

                    // have to wait until attributes have been parsed before creating element
                    // attributes may contain namespace info used by the element
                    XmlElement element = CreateElement(propertyName, document, elementPrefix, manager);

                    currentNode.AppendChild(element);

                    // add attributes to newly created element
                    foreach (KeyValuePair <string, string> nameValue in attributeNameValues)
                    {
                        string attributePrefix = GetPrefix(nameValue.Key);

                        XmlAttribute attribute = (!string.IsNullOrEmpty(attributePrefix))
                      ? document.CreateAttribute(nameValue.Key, manager.LookupNamespace(attributePrefix))
                      : document.CreateAttribute(nameValue.Key);

                        attribute.Value = nameValue.Value;

                        element.SetAttributeNode(attribute);
                    }

                    if (reader.TokenType == JsonToken.String)
                    {
                        element.AppendChild(document.CreateTextNode(reader.Value.ToString()));
                    }
                    else if (reader.TokenType == JsonToken.Integer)
                    {
                        element.AppendChild(document.CreateTextNode(XmlConvert.ToString((long)reader.Value)));
                    }
                    else if (reader.TokenType == JsonToken.Float)
                    {
                        element.AppendChild(document.CreateTextNode(XmlConvert.ToString((double)reader.Value)));
                    }
                    else if (reader.TokenType == JsonToken.Boolean)
                    {
                        element.AppendChild(document.CreateTextNode(XmlConvert.ToString((bool)reader.Value)));
                    }
                    else if (reader.TokenType == JsonToken.Date)
                    {
                        DateTime d = (DateTime)reader.Value;
                        element.AppendChild(document.CreateTextNode(XmlConvert.ToString(d, DateTimeUtils.ToSerializationMode(d.Kind))));
                    }
                    else if (reader.TokenType == JsonToken.Null)
                    {
                        // empty element. do nothing
                    }
                    else
                    {
                        // finished element will have no children to deserialize
                        if (!finishedElement)
                        {
                            manager.PushScope();

                            DeserializeNode(reader, document, manager, element);

                            manager.PopScope();
                        }
                    }
                }
                break;
            }
        }
コード例 #17
0
        /// <summary>
        /// Internal method which generates the RDF/Json Output for a Graph
        /// </summary>
        /// <param name="context">Writer Context</param>
        private void GenerateOutput(RdfXmlWriterContext context)
        {
            context.UseDtd = this._useDTD;

            //Create required variables
            int           nextNamespaceID = 0;
            List <String> tempNamespaces  = new List <String>();

            //Always force RDF Namespace to be correctly defined
            context.Graph.NamespaceMap.AddNamespace("rdf", UriFactory.Create(NamespaceMapper.RDF));

            //Create an XML Document
            XmlDocument    doc  = new XmlDocument();
            XmlDeclaration decl = doc.CreateXmlDeclaration("1.0", "UTF-8", null);

            doc.AppendChild(decl);

            //Create the DOCTYPE declaration and the rdf:RDF element
            StringBuilder entities = new StringBuilder();
            XmlElement    rdf      = doc.CreateElement("rdf:RDF", NamespaceMapper.RDF);

            if (context.Graph.BaseUri != null)
            {
                XmlAttribute baseUri = doc.CreateAttribute("xml:base");
                baseUri.Value = Uri.EscapeUriString(context.Graph.BaseUri.ToString());
                rdf.Attributes.Append(baseUri);
            }

            XmlAttribute ns;
            String       uri;

            entities.Append('\n');
            foreach (String prefix in context.Graph.NamespaceMap.Prefixes)
            {
                uri = context.Graph.NamespaceMap.GetNamespaceUri(prefix).ToString();
                if (!prefix.Equals(String.Empty))
                {
                    entities.AppendLine("\t<!ENTITY " + prefix + " '" + uri + "'>");
                    ns       = doc.CreateAttribute("xmlns:" + prefix);
                    ns.Value = Uri.EscapeUriString(uri.Replace("'", "&apos;"));
                }
                else
                {
                    ns       = doc.CreateAttribute("xmlns");
                    ns.Value = Uri.EscapeUriString(uri);
                }
                rdf.Attributes.Append(ns);
            }
            if (context.UseDtd)
            {
                XmlDocumentType doctype = doc.CreateDocumentType("rdf:RDF", null, null, entities.ToString());
                doc.AppendChild(doctype);
            }
            doc.AppendChild(rdf);

            //Find the Collections
            if (this._compressionLevel >= WriterCompressionLevel.More)
            {
                WriterHelper.FindCollections(context);
            }

            //Find the Type References
            Dictionary <INode, String> typerefs = this.FindTypeReferences(context, ref nextNamespaceID, tempNamespaces, doc);

            //Get the Triples as a Sorted List
            List <Triple> ts = context.Graph.Triples.Where(t => !context.TriplesDone.Contains(t)).ToList();

            ts.Sort();

            //Variables we need to track our writing
            INode lastSubj, lastPred;

            lastSubj = lastPred = null;
            XmlElement subj, pred;

            //Initialise stuff to keep the compiler happy
            subj = doc.CreateElement("rdf:Description", NamespaceMapper.RDF);
            pred = doc.CreateElement("temp");

            for (int i = 0; i < ts.Count; i++)
            {
                Triple t = ts[i];
                if (context.TriplesDone.Contains(t))
                {
                    continue;                                  //Skip if already done
                }
                if (lastSubj == null || !t.Subject.Equals(lastSubj))
                {
                    //Start a new set of Triples
                    //Validate Subject
                    //Use a Type Reference if applicable
                    if (typerefs.ContainsKey(t.Subject))
                    {
                        String tref = typerefs[t.Subject];
                        String tprefix;
                        if (tref.StartsWith(":"))
                        {
                            tprefix = String.Empty;
                        }
                        else if (tref.Contains(":"))
                        {
                            tprefix = tref.Substring(0, tref.IndexOf(':'));
                        }
                        else
                        {
                            tprefix = String.Empty;
                        }
                        subj = doc.CreateElement(tref, context.Graph.NamespaceMap.GetNamespaceUri(tprefix).ToString());
                    }
                    else
                    {
                        subj = doc.CreateElement("rdf:Description", NamespaceMapper.RDF);
                    }

                    //Write out the Subject
                    doc.DocumentElement.AppendChild(subj);
                    lastSubj = t.Subject;

                    //Apply appropriate attributes
                    switch (t.Subject.NodeType)
                    {
                    case NodeType.GraphLiteral:
                        throw new RdfOutputException(WriterErrorMessages.GraphLiteralsUnserializable("RDF/XML"));

                    case NodeType.Literal:
                        throw new RdfOutputException(WriterErrorMessages.LiteralSubjectsUnserializable("RDF/XML"));

                    case NodeType.Blank:
                        if (context.Collections.ContainsKey(t.Subject))
                        {
                            this.GenerateCollectionOutput(context, t.Subject, subj, ref nextNamespaceID, tempNamespaces, doc);
                        }
                        else
                        {
                            XmlAttribute nodeID = doc.CreateAttribute("rdf:nodeID", NamespaceMapper.RDF);
                            nodeID.Value = context.BlankNodeMapper.GetOutputID(((IBlankNode)t.Subject).InternalID);
                            subj.Attributes.Append(nodeID);
                        }
                        break;

                    case NodeType.Uri:
                        this.GenerateUriOutput(context, (IUriNode)t.Subject, "rdf:about", tempNamespaces, subj, doc);
                        break;

                    default:
                        throw new RdfOutputException(WriterErrorMessages.UnknownNodeTypeUnserializable("RDF/XML"));
                    }

                    //Write the Predicate
                    pred = this.GeneratePredicateNode(context, t.Predicate, ref nextNamespaceID, tempNamespaces, doc, subj);
                    subj.AppendChild(pred);
                    lastPred = t.Predicate;
                }
                else if (lastPred == null || !t.Predicate.Equals(lastPred))
                {
                    //Write the Predicate
                    pred = this.GeneratePredicateNode(context, t.Predicate, ref nextNamespaceID, tempNamespaces, doc, subj);
                    subj.AppendChild(pred);
                    lastPred = t.Predicate;
                }

                //Write the Object
                //Create an Object for the Object
                switch (t.Object.NodeType)
                {
                case NodeType.Blank:
                    if (pred.HasChildNodes || pred.HasAttributes)
                    {
                        //Require a new Predicate
                        pred = this.GeneratePredicateNode(context, t.Predicate, ref nextNamespaceID, tempNamespaces, doc, subj);
                        subj.AppendChild(pred);
                    }

                    if (context.Collections.ContainsKey(t.Object))
                    {
                        //Output a Collection
                        this.GenerateCollectionOutput(context, t.Object, pred, ref nextNamespaceID, tempNamespaces, doc);
                    }
                    else
                    {
                        //Terminate the Blank Node triple by adding a rdf:nodeID attribute
                        XmlAttribute nodeID = doc.CreateAttribute("rdf:nodeID", NamespaceMapper.RDF);
                        nodeID.Value = context.BlankNodeMapper.GetOutputID(((IBlankNode)t.Object).InternalID);
                        pred.Attributes.Append(nodeID);
                    }

                    //Force a new Predicate after Blank Nodes
                    lastPred = null;

                    break;

                case NodeType.GraphLiteral:
                    throw new RdfOutputException(WriterErrorMessages.GraphLiteralsUnserializable("RDF/XML"));

                case NodeType.Literal:
                    ILiteralNode lit = (ILiteralNode)t.Object;

                    if (pred.HasChildNodes || pred.HasAttributes)
                    {
                        //Require a new Predicate
                        pred = this.GeneratePredicateNode(context, t.Predicate, ref nextNamespaceID, tempNamespaces, doc, subj);
                        subj.AppendChild(pred);
                    }

                    this.GenerateLiteralOutput(context, lit, pred, doc);

                    //Force a new Predicate Node after Literals
                    lastPred = null;

                    break;

                case NodeType.Uri:

                    this.GenerateUriOutput(context, (IUriNode)t.Object, "rdf:resource", tempNamespaces, pred, doc);

                    //Force a new Predicate Node after URIs
                    lastPred = null;

                    break;

                default:
                    throw new RdfOutputException(WriterErrorMessages.UnknownNodeTypeUnserializable("RDF/XML"));
                }

                context.TriplesDone.Add(t);
            }

            //Check we haven't failed to output any collections
            foreach (KeyValuePair <INode, OutputRdfCollection> pair in context.Collections)
            {
                if (!pair.Value.HasBeenWritten)
                {
                    if (typerefs.ContainsKey(pair.Key))
                    {
                        String tref = typerefs[pair.Key];
                        String tprefix;
                        if (tref.StartsWith(":"))
                        {
                            tref    = tref.Substring(1);
                            tprefix = String.Empty;
                        }
                        else if (tref.Contains(":"))
                        {
                            tprefix = tref.Substring(0, tref.IndexOf(':'));
                        }
                        else
                        {
                            tprefix = String.Empty;
                        }
                        subj = doc.CreateElement(tref, context.Graph.NamespaceMap.GetNamespaceUri(tprefix).ToString());

                        doc.DocumentElement.AppendChild(subj);

                        this.GenerateCollectionOutput(context, pair.Key, subj, ref nextNamespaceID, tempNamespaces, doc);
                    }
                    else
                    {
                        //Generate an rdf:Description Node with a rdf:nodeID on it
                        XmlElement   colNode = doc.CreateElement("rdf:Description");
                        XmlAttribute nodeID  = doc.CreateAttribute("rdf:nodeID");
                        nodeID.Value = context.BlankNodeMapper.GetOutputID(((IBlankNode)pair.Key).InternalID);
                        colNode.Attributes.Append(nodeID);
                        doc.DocumentElement.AppendChild(colNode);
                        this.GenerateCollectionOutput(context, pair.Key, colNode, ref nextNamespaceID, tempNamespaces, doc);
                        //throw new RdfOutputException("Failed to output a Collection due to an unknown error");
                    }
                }
            }

            //Save to the Output Stream
            InternalXmlWriter writer = new InternalXmlWriter();

            writer.Save(context.Output, doc);

            //Get rid of the Temporary Namespace
            foreach (String tempPrefix in tempNamespaces)
            {
                context.Graph.NamespaceMap.RemoveNamespace(tempPrefix);
            }
        }
コード例 #18
0
        private void btnExport_Click(object sender, EventArgs e)
        {
            #region 1.使用SaveFileDiaLog选择保存路径
            string fileName = string.Empty;
            using (SaveFileDialog sfd = new SaveFileDialog())
            {
                sfd.Title  = "选择保存路径";
                sfd.Filter = "Xml|*.xml";
                //☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆这是注意设置要保存的文件的默认文件名
                sfd.FileName = "AreaInfo.xml";//虽然只是给了文件的默认名,但是是自动生成全路径的
                if (sfd.ShowDialog() != DialogResult.OK)
                {
                    return;
                }
                fileName = sfd.FileName;//获取的是全路径
            }
            #endregion

            #region 2.从数据库查询数据写入XML
            string connStr = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
            using (SqlConnection conn = new SqlConnection(connStr))
            {
                using (SqlCommand cmd = conn.CreateCommand()) //new SqlCommand())
                {
                    conn.Open();
                    //cmd.Connection = conn;

                    cmd.CommandText = "SELECT  [AreaId],[AreaName],[AreaPid] FROM [db_Tome1].[dbo].[AreaFull]";

                    using (SqlDataReader reader = cmd.ExecuteReader())
                    {
                        XmlDocument    doc = new XmlDocument();
                        XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);

                        doc.AppendChild(dec);

                        XmlElement Areas = doc.CreateElement("Areas");
                        doc.AppendChild(Areas);

                        while (reader.Read())
                        {
                            //注意我们是使用DOM的方式写入到XML文件的
                            //所以我们新建了一个AreaInfo类
                            int      areaId   = int.Parse(reader["AreaId"].ToString());
                            string   areaName = reader["AreaName"].ToString();
                            int      areaPid  = int.Parse(reader["AreaPid"].ToString());
                            AreaInfo temp     = new AreaInfo(areaId, areaName, areaPid);


                            XmlElement Area = doc.CreateElement("Area");
                            Area.SetAttribute("ID", temp.AreaId.ToString());
                            Areas.AppendChild(Area);

                            XmlElement AreaName = doc.CreateElement("AreaName");
                            AreaName.InnerXml = temp.AreaName;
                            Area.AppendChild(AreaName);

                            XmlElement AreaPid = doc.CreateElement("AreaPid");
                            AreaPid.InnerXml = temp.AreaPid.ToString();
                            Area.AppendChild(AreaPid);
                        }
                        doc.Save(fileName);//注意这个fileName 是全路径,包括了文件的名字
                        MessageBox.Show("保存成功!");
                    }//end using reader
                } //end using cmd
            }     //end using conn
            #endregion
        }
コード例 #19
0
        private static void AddDelaration(XmlDocument doc)
        {
            XmlDeclaration decl = doc.CreateXmlDeclaration("1.0", "utf-8", null);

            doc.InsertBefore(decl, doc.DocumentElement);
        }
コード例 #20
0
    // Test adding an XML declaration to the document.
    public void TestXmlDocumentAddXmlDeclaration()
    {
        XmlDocument doc = new XmlDocument();

        // Add the declaration.
        XmlDeclaration decl =
            doc.CreateXmlDeclaration("1.0", null, null);

        AssertNull("XmlDeclaration (1)", decl.ParentNode);
        AssertEquals("XmlDeclaration (2)", doc, decl.OwnerDocument);
        doc.AppendChild(decl);
        AssertEquals("XmlDeclaration (3)", doc, decl.ParentNode);
        AssertEquals("XmlDeclaration (4)", doc, decl.OwnerDocument);

        // Try to add it again, which should fail this time.
        try
        {
            doc.AppendChild(decl);
            Fail("adding XmlDeclaration node twice");
        }
        catch (InvalidOperationException)
        {
            // Success
        }
        try
        {
            doc.PrependChild(decl);
            Fail("prepending XmlDeclaration node twice");
        }
        catch (InvalidOperationException)
        {
            // Success
        }

        // Adding a document type before should fail.
        XmlDocumentType type =
            doc.CreateDocumentType("foo", null, null, null);

        try
        {
            doc.PrependChild(type);
            Fail("prepending XmlDocumentType");
        }
        catch (InvalidOperationException)
        {
            // Success
        }

        // Adding a document type after should succeed.
        doc.AppendChild(type);

        // Adding an element before should fail.
        XmlElement element = doc.CreateElement("foo");

        try
        {
            doc.PrependChild(element);
            Fail("prepending XmlElement");
        }
        catch (InvalidOperationException)
        {
            // Success
        }

        // Adding the element between decl and type should fail.
        try
        {
            doc.InsertAfter(element, decl);
            Fail("inserting XmlElement between XmlDeclaration " +
                 "and XmlDocumentType");
        }
        catch (InvalidOperationException)
        {
            // Success
        }
        try
        {
            doc.InsertBefore(element, type);
            Fail("inserting XmlElement between XmlDeclaration " +
                 "and XmlDocumentType (2)");
        }
        catch (InvalidOperationException)
        {
            // Success
        }

        // Adding an element after should succeed.
        doc.AppendChild(element);
    }
コード例 #21
0
ファイル: Options.cs プロジェクト: v0icer/poltools
        public static void Save()
        {
            string FileName = Path.Combine(FiddlerControls.Options.AppDataPath, FiddlerControls.Options.ProfileName);

            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", FiddlerControls.Options.OutputPath.ToString());
            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", FiddlerControls.Options.ArtItemSizeWidth.ToString());
            elem.SetAttribute("height", FiddlerControls.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", FiddlerControls.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", FiddlerControls.Options.DesignAlternative.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("Definies 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", FiddlerControls.Options.MapCmd);
            elem.SetAttribute("args", FiddlerControls.Options.MapArgs);
            sr.AppendChild(elem);

            comment = dom.CreateComment("Definies the map names");
            sr.AppendChild(comment);
            elem = dom.CreateElement("MapNames");
            elem.SetAttribute("map0", FiddlerControls.Options.MapNames[0]);
            elem.SetAttribute("map1", FiddlerControls.Options.MapNames[1]);
            elem.SetAttribute("map2", FiddlerControls.Options.MapNames[2]);
            elem.SetAttribute("map3", FiddlerControls.Options.MapNames[3]);
            elem.SetAttribute("map4", FiddlerControls.Options.MapNames[4]);
            elem.SetAttribute("map5", FiddlerControls.Options.MapNames[5]);
            sr.AppendChild(elem);

            comment = dom.CreateComment("Extern Tools settings");
            sr.AppendChild(comment);
            if (ExternTools != null)
            {
                foreach (ExternTool tool in ExternTools)
                {
                    XmlElement xtool = dom.CreateElement("ExternTool");
                    xtool.SetAttribute("name", tool.Name);
                    xtool.SetAttribute("path", tool.FileName);
                    for (int i = 0; i < tool.Args.Count; i++)
                    {
                        XmlElement xarg = dom.CreateElement("Args");
                        xarg.SetAttribute("name", tool.ArgsName[i]);
                        xarg.SetAttribute("arg", tool.Args[i]);
                        xtool.AppendChild(xarg);
                    }
                    sr.AppendChild(xtool);
                }
            }

            comment = dom.CreateComment("Loaded Plugins");
            sr.AppendChild(comment);
            if (FiddlerControls.Options.PluginsToLoad != null)
            {
                foreach (string plug in FiddlerControls.Options.PluginsToLoad)
                {
                    XmlElement xplug = dom.CreateElement("Plugin");
                    xplug.SetAttribute("name", plug);
                    sr.AppendChild(xplug);
                }
            }

            comment = dom.CreateComment("Pathsettings");
            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.ToString());
                path.SetAttribute("value", Files.MulPath[key].ToString());
                sr.AppendChild(path);
            }
            dom.AppendChild(sr);

            comment = dom.CreateComment("Disabled Tab Views");
            sr.AppendChild(comment);
            foreach (KeyValuePair <int, bool> kvp in FiddlerControls.Options.ChangedViewState)
            {
                if (!kvp.Value)
                {
                    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", FiddlerControls.Options.TileDataDirectlySaveOnChange.ToString());
            sr.AppendChild(elem);

            dom.Save(FileName);
        }
コード例 #22
0
    // Test adding an element to the document.
    public void TestXmlDocumentAddElement()
    {
        XmlDocument doc = new XmlDocument();

        // Add an element to the document.
        XmlElement element = doc.CreateElement("foo");

        AssertNull("XmlElement (1)", element.ParentNode);
        AssertEquals("XmlElement (2)", doc, element.OwnerDocument);
        doc.AppendChild(element);
        AssertEquals("XmlElement (3)", doc, element.ParentNode);
        AssertEquals("XmlElement (4)", doc, element.OwnerDocument);

        // Try to add it again, which should fail this time.
        try
        {
            doc.AppendChild(element);
            Fail("adding XmlElement node twice");
        }
        catch (InvalidOperationException)
        {
            // Success
        }
        try
        {
            doc.PrependChild(element);
            Fail("prepending XmlElement node twice");
        }
        catch (InvalidOperationException)
        {
            // Success
        }

        // Adding an XmlDeclaration after should fail.
        XmlDeclaration decl =
            doc.CreateXmlDeclaration("1.0", null, null);

        try
        {
            doc.AppendChild(decl);
            Fail("appending XmlDeclaration after XmlElement");
        }
        catch (InvalidOperationException)
        {
            // Success
        }

        // But adding XmlDeclaration before should succeed.
        doc.PrependChild(decl);

        // Adding a document type after should fail.
        XmlDocumentType type =
            doc.CreateDocumentType("foo", null, null, null);

        try
        {
            doc.AppendChild(type);
            Fail("appending XmlDocumentType");
        }
        catch (InvalidOperationException)
        {
            // Success
        }

        // Adding a document type before should succeed.
        doc.InsertBefore(type, element);
    }
コード例 #23
0
        public override void ExportData(CanvasData data, params object[] args)
        {
            if (args == null || args.Length != 1 || args[0].GetType() != typeof(string))
            {
                throw new ArgumentException("Location Arguments");
            }
            string path = (string)args[0];

            XmlDocument    saveDoc = new XmlDocument();
            XmlDeclaration decl    = saveDoc.CreateXmlDeclaration("1.0", "UTF-8", null);

            saveDoc.InsertBefore(decl, saveDoc.DocumentElement);

            // CANVAS

            XmlElement canvas = saveDoc.CreateElement("NodeCanvas");

            canvas.SetAttribute("type", data.type.FullName);
            saveDoc.AppendChild(canvas);

            // EDITOR STATES

            XmlElement editorStates = saveDoc.CreateElement("EditorStates");

            canvas.AppendChild(editorStates);
            foreach (EditorStateData stateData in data.editorStates)
            {
                XmlElement editorState = saveDoc.CreateElement("EditorState");
                editorState.SetAttribute("selected", stateData.selectedNode != null ? stateData.selectedNode.nodeID.ToString() : "");
                editorState.SetAttribute("pan", stateData.panOffset.x + "," + stateData.panOffset.y);
                editorState.SetAttribute("zoom", stateData.zoom.ToString());
                editorStates.AppendChild(editorState);
            }

            // GROUPS

            XmlElement groups = saveDoc.CreateElement("Groups");

            canvas.AppendChild(groups);
            foreach (GroupData groupData in data.groups)
            {
                XmlElement group = saveDoc.CreateElement("Group");
                group.SetAttribute("name", groupData.name);
                group.SetAttribute("rect", groupData.rect.x + "," + groupData.rect.y + "," + groupData.rect.width + "," + groupData.rect.height);
                group.SetAttribute("color", groupData.color.r + "," + groupData.color.g + "," + groupData.color.b + "," + groupData.color.a);
                groups.AppendChild(group);
            }

            // NODES

            XmlElement nodes = saveDoc.CreateElement("Nodes");

            canvas.AppendChild(nodes);
            foreach (NodeData nodeData in data.nodes.Values)
            {
                XmlElement node = saveDoc.CreateElement("Node");
                node.SetAttribute("name", nodeData.name);
                node.SetAttribute("ID", nodeData.nodeID.ToString());
                node.SetAttribute("type", nodeData.typeID);
                node.SetAttribute("pos", nodeData.nodePos.x + "," + nodeData.nodePos.y);
                nodes.AppendChild(node);

                // NODE PORTS

                foreach (PortData portData in nodeData.connectionPorts)
                {
                    XmlElement port = saveDoc.CreateElement("Port");
                    port.SetAttribute("ID", portData.portID.ToString());
                    port.SetAttribute("name", portData.name);
                    port.SetAttribute("dynamic", portData.dynamic.ToString());
                    if (portData.dynamic)
                    {                     // Serialize dynamic port
                        port.SetAttribute("type", portData.dynaType.FullName);
                        foreach (string fieldName in portData.port.AdditionalDynamicKnobData())
                        {
                            SerializeFieldToXML(port, portData.port, fieldName);                             // Serialize all dynamic knob variables
                        }
                    }
                    node.AppendChild(port);
                }

                // NODE VARIABLES

                foreach (VariableData varData in nodeData.variables)
                {                 // Serialize all node variables
                    if (varData.refObject != null)
                    {             // Serialize reference-type variables as 'Variable' element
                        XmlElement variable = saveDoc.CreateElement("Variable");
                        variable.SetAttribute("name", varData.name);
                        variable.SetAttribute("refID", varData.refObject.refID.ToString());
                        node.AppendChild(variable);
                    }
                    else                     // Serialize value-type fields in-line
                    {
                        SerializeFieldToXML(node, nodeData.node, varData.name);
                    }
                }
            }

            // CONNECTIONS

            XmlElement connections = saveDoc.CreateElement("Connections");

            canvas.AppendChild(connections);
            foreach (ConnectionData connectionData in data.connections)
            {
                XmlElement connection = saveDoc.CreateElement("Connection");
                connection.SetAttribute("port1ID", connectionData.port1.portID.ToString());
                connection.SetAttribute("port2ID", connectionData.port2.portID.ToString());
                connections.AppendChild(connection);
            }

            // OBJECTS

            XmlElement objects = saveDoc.CreateElement("Objects");

            canvas.AppendChild(objects);
            foreach (ObjectData objectData in data.objects.Values)
            {
                XmlElement obj = saveDoc.CreateElement("Object");
                obj.SetAttribute("refID", objectData.refID.ToString());
                obj.SetAttribute("type", objectData.data.GetType().FullName);
                objects.AppendChild(obj);
                SerializeObjectToXML(obj, objectData.data);
            }

            // WRITE

            Directory.CreateDirectory(Path.GetDirectoryName(path));
            using (XmlTextWriter writer = new XmlTextWriter(path, Encoding.UTF8))
            {
                writer.Formatting  = Formatting.Indented;
                writer.Indentation = 1;
                writer.IndentChar  = '\t';
                saveDoc.Save(writer);
            }
        }
コード例 #24
0
        public void createRole()
        {
            Console.WriteLine("Выберите тип учетки для (1 cop / 2 студент)");
            string role = Console.ReadLine();

            switch (role)
            {
            default:
                break;

            case "1":
            {
                string path = Directory.GetCurrentDirectory() + "\\XML\\cop.xml";
                if (File.Exists(path))
                {
                    #region добавляем в существующий
                    XmlDocument xdoc = new XmlDocument();
                    xdoc.Load(path);
                    XmlElement rootx = xdoc.DocumentElement;

                    Console.WriteLine("Введите имя cop");
                    string name = Console.ReadLine();
                    Console.WriteLine("Введите фамилию cop");
                    string sname = Console.ReadLine();
                    Console.WriteLine("Введите возраст cop");
                    string age = Console.ReadLine();
                    int    id  = Convert.ToInt32(rootx.LastChild.Attributes[0].Value) + 1;
                    Console.WriteLine("ID cop сгенерировано: {0}", id);
                    string pass = "******";

                    XmlElement copx = xdoc.CreateElement("cop");
                    copx.SetAttribute("ID", Convert.ToString(id));
                    XmlElement namex = xdoc.CreateElement("Name");
                    namex.InnerText = name;
                    XmlElement snamex = xdoc.CreateElement("Surname");
                    snamex.InnerText = sname;
                    XmlElement agex = xdoc.CreateElement("Age");
                    agex.InnerText = age;
                    XmlElement passx = xdoc.CreateElement("Passsword");
                    passx.InnerText = pass;
                    XmlElement activationx = xdoc.CreateElement("Active");
                    activationx.InnerText = "false";


                    rootx.AppendChild(copx);
                    copx.AppendChild(namex);
                    copx.AppendChild(snamex);
                    copx.AppendChild(agex);
                    copx.AppendChild(passx);
                    copx.AppendChild(activationx);

                    xdoc.AppendChild(rootx);

                    xdoc.Save(path);

                    Console.WriteLine("COP создан {0}, пароль поумолчанию 123456789");
                    #endregion
                }
                else
                {
                    #region Создаем
                    if (!File.Exists(path))
                    {
                        Directory.CreateDirectory(path.Substring(0, path.LastIndexOf('\\')));
                    }
                    Console.WriteLine("Файла не существует. Создать?(да/нет)");
                    string choice = Console.ReadLine();
                    switch (choice)
                    {
                    default:
                        break;

                    case "да":
                    {
                        #region
                        Console.WriteLine("Введите имя cop");
                        string name = Console.ReadLine();
                        Console.WriteLine("Введите фамилию cop");
                        string sname = Console.ReadLine();
                        Console.WriteLine("Введите возраст cop");
                        string age = Console.ReadLine();
                        int    id  = 100000;
                        Console.WriteLine("ID студента сгенерировано: {0}", id);

                        string pass = "******";

                        XmlDocument    xdoc    = new XmlDocument();
                        XmlDeclaration xmldecl = xdoc.CreateXmlDeclaration("1.0", "utf-8", null);

                        xdoc.AppendChild(xmldecl);

                        XmlElement rootx    = xdoc.CreateElement("COPS");
                        XmlElement studentx = xdoc.CreateElement("cop");
                        studentx.SetAttribute("ID", Convert.ToString(id));
                        XmlElement namex = xdoc.CreateElement("Name");
                        namex.InnerText = name;
                        XmlElement snamex = xdoc.CreateElement("Surname");
                        snamex.InnerText = sname;
                        XmlElement agex = xdoc.CreateElement("Age");
                        agex.InnerText = age;
                        XmlElement passx = xdoc.CreateElement("Passsword");
                        passx.InnerText = pass;
                        XmlElement activationx = xdoc.CreateElement("Active");
                        activationx.InnerText = "false";

                        rootx.AppendChild(studentx);
                        studentx.AppendChild(namex);
                        studentx.AppendChild(snamex);
                        studentx.AppendChild(agex);
                        studentx.AppendChild(passx);
                        studentx.AppendChild(activationx);

                        xdoc.AppendChild(rootx);
                        xdoc.Save(path);
                        Console.WriteLine("COP создан {0}, пароль поумолчанию 123456789");
                        #endregion
                    }
                    break;

                    case "нет": break;
                    }
                    #endregion
                }
            }
            break;

            case "2":
            {
                string path = Directory.GetCurrentDirectory() + "\\XML\\student.xml";
                if (File.Exists(path))
                {
                    #region добавляем в существующий
                    XmlDocument xdoc = new XmlDocument();
                    xdoc.Load(path);
                    XmlElement rootx = xdoc.DocumentElement;

                    Console.WriteLine("Введите имя студента");
                    string name = Console.ReadLine();
                    Console.WriteLine("Введите фамилию студента");
                    string sname = Console.ReadLine();
                    Console.WriteLine("Введите возраст студента");
                    string age = Console.ReadLine();
                    int    id  = Convert.ToInt32(rootx.LastChild.Attributes[0].Value) + 1;
                    Console.WriteLine("ID студента сгенерировано: {0}", id);
                    Console.WriteLine("Введите путь до CV");
                    string pass   = "******";
                    string pathCV = Console.ReadLine();
                    Console.WriteLine("Введите текст критерия 1");
                    string criteria1 = Console.ReadLine();
                    Console.WriteLine("Введите текст критерия 2");
                    string criteria2 = Console.ReadLine();
                    Console.WriteLine("Введите текст критерия 3");
                    string criteria3 = Console.ReadLine();


                    XmlElement studentx = xdoc.CreateElement("student");
                    studentx.SetAttribute("ID", Convert.ToString(id));
                    XmlElement namex = xdoc.CreateElement("Name");
                    namex.InnerText = name;
                    XmlElement snamex = xdoc.CreateElement("Surname");
                    snamex.InnerText = sname;
                    XmlElement agex = xdoc.CreateElement("Age");
                    agex.InnerText = age;
                    XmlElement passx = xdoc.CreateElement("Passsword");
                    passx.InnerText = pass;
                    XmlElement pathCVx = xdoc.CreateElement("CVpath");
                    pathCVx.InnerText = pathCV;
                    XmlElement criteria1x = xdoc.CreateElement("Criteria1");
                    criteria1x.InnerText = criteria1;
                    XmlElement criteria2x = xdoc.CreateElement("Criteria2");
                    criteria2x.InnerText = criteria2;
                    XmlElement criteria3x = xdoc.CreateElement("Criteria3");
                    criteria3x.InnerText = criteria3;
                    XmlElement activationx = xdoc.CreateElement("Active");
                    activationx.InnerText = "false";


                    rootx.AppendChild(studentx);
                    studentx.AppendChild(namex);
                    studentx.AppendChild(snamex);
                    studentx.AppendChild(agex);
                    studentx.AppendChild(passx);
                    studentx.AppendChild(pathCVx);
                    studentx.AppendChild(activationx);
                    studentx.AppendChild(criteria1x);
                    studentx.AppendChild(criteria2x);
                    studentx.AppendChild(criteria3x);
                    xdoc.AppendChild(rootx);

                    xdoc.Save(path);

                    Console.WriteLine("Студент создан {0}, пароль поумолчанию 123456789");
                    #endregion
                }
                else
                {
                    #region Создаем
                    if (!File.Exists(path))
                    {
                        Directory.CreateDirectory(path.Substring(0, path.LastIndexOf('\\')));
                    }
                    Console.WriteLine("Файла не существует. Создать?(да/нет)");
                    string choice = Console.ReadLine();
                    switch (choice)
                    {
                    default:
                        break;

                    case "да":
                    {
                        #region
                        Console.WriteLine("Введите имя студента");
                        string name = Console.ReadLine();
                        Console.WriteLine("Введите фамилию студента");
                        string sname = Console.ReadLine();
                        Console.WriteLine("Введите возраст студента");
                        string age = Console.ReadLine();
                        int    id  = 100000;
                        Console.WriteLine("ID студента сгенерировано: {0}", id);
                        Console.WriteLine("Введите путь до CV");
                        string pass   = "******";
                        string pathCV = Console.ReadLine();
                        Console.WriteLine("Введите текст критерия 1");
                        string criteria1 = Console.ReadLine();
                        Console.WriteLine("Введите текст критерия 2");
                        string criteria2 = Console.ReadLine();
                        Console.WriteLine("Введите текст критерия 3");
                        string criteria3 = Console.ReadLine();

                        XmlDocument    xdoc    = new XmlDocument();
                        XmlDeclaration xmldecl = xdoc.CreateXmlDeclaration("1.0", "utf-8", null);

                        xdoc.AppendChild(xmldecl);

                        XmlElement rootx    = xdoc.CreateElement("Students");
                        XmlElement studentx = xdoc.CreateElement("student");
                        studentx.SetAttribute("ID", Convert.ToString(id));
                        XmlElement namex = xdoc.CreateElement("Name");
                        namex.InnerText = name;
                        XmlElement snamex = xdoc.CreateElement("Surname");
                        snamex.InnerText = sname;
                        XmlElement agex = xdoc.CreateElement("Age");
                        agex.InnerText = age;
                        XmlElement passx = xdoc.CreateElement("Passsword");
                        passx.InnerText = pass;
                        XmlElement pathCVx     = xdoc.CreateElement("CVpath");
                        XmlElement activationx = xdoc.CreateElement("Active");
                        activationx.InnerText = "false";
                        XmlElement criteria1x = xdoc.CreateElement("Criteria1");
                        criteria1x.InnerText = criteria1;
                        XmlElement criteria2x = xdoc.CreateElement("Criteria2");
                        criteria2x.InnerText = criteria2;
                        XmlElement criteria3x = xdoc.CreateElement("Criteria3");
                        criteria3x.InnerText = criteria3;

                        rootx.AppendChild(studentx);
                        studentx.AppendChild(namex);
                        studentx.AppendChild(snamex);
                        studentx.AppendChild(agex);
                        studentx.AppendChild(passx);
                        studentx.AppendChild(pathCVx);
                        studentx.AppendChild(activationx);
                        studentx.AppendChild(criteria1x);
                        studentx.AppendChild(criteria2x);
                        studentx.AppendChild(criteria3x);

                        xdoc.AppendChild(rootx);
                        xdoc.Save(path);
                        Console.WriteLine("Студент создан {0}, пароль поумолчанию 123456789");
                        #endregion
                    }
                    break;

                    case "нет": break;
                    }
                    #endregion
                }
            }
            break;
            }
        }
コード例 #25
0
        public void Save()
        {
            XmlDocument xml;
            XmlElement  root;
            XmlElement  element;
            XmlText     text;
            XmlComment  xmlComment;

            string sPath = Process.GetCurrentProcess().MainModule.FileName;

            sPath = Path.GetDirectoryName(sPath);

            sPath = Path.Combine(sPath, _cfgFile);

            if (!Directory.Exists(sPath))
            {
                Logging.WriteDebug("Creating config directory");
                Directory.CreateDirectory(sPath);
            }

            String serverName = Lua.GetReturnVal <string>("return GetRealmName()", 0);
            String toonName   = ObjectManager.Me.Name;

            sPath = Path.Combine(sPath, "DBWarlock-" + serverName + "-" + toonName + ".config");
            //((Warlock)Global.CurrentCC).slog("");
            //Logging.Write("");

            Logging.WriteDebug("Saving config file: {0}", sPath);
            xml = new XmlDocument();
            XmlDeclaration dc = xml.CreateXmlDeclaration("1.0", "utf-8", null);

            xml.AppendChild(dc);

            xmlComment = xml.CreateComment(
                "=======================================================================\n" +
                "Configuration file for the DBWarlock CC\n\n" +
                "XML file containing settings to customize the the DBWarlock CC.\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("DBWarlockSettings");
            root.AppendChild(xmlComment);

            //let's add another element (child of the root)
            element = xml.CreateElement("showDebug");
            text    = xml.CreateTextNode(showDebug.ToString());
            element.AppendChild(text);
            root.AppendChild(element);

            //let's add another element (child of the root)
            element = xml.CreateElement("restManaPercent");
            text    = xml.CreateTextNode(restManaPercent.ToString());
            element.AppendChild(text);
            root.AppendChild(element);

            //let's add another element (child of the root)
            element = xml.CreateElement("restHealthPercent");
            text    = xml.CreateTextNode(restHealthPercent.ToString());
            element.AppendChild(text);
            root.AppendChild(element);

            //let's add another element (child of the root)
            element = xml.CreateElement("maxSoulShards");
            text    = xml.CreateTextNode(maxSoulShards.ToString());
            element.AppendChild(text);
            root.AppendChild(element);

            //let's add another element (child of the root)
            element = xml.CreateElement("healthStoneHealthPercent");
            text    = xml.CreateTextNode(healthStoneHealthPercent.ToString());
            element.AppendChild(text);
            root.AppendChild(element);

            //let's add another element (child of the root)
            element = xml.CreateElement("useFirestone");
            text    = xml.CreateTextNode(useFirestone.ToString());
            element.AppendChild(text);
            root.AppendChild(element);

            //let's add another element (child of the root)
            element = xml.CreateElement("useSpellstone");
            text    = xml.CreateTextNode(useSpellstone.ToString());
            element.AppendChild(text);
            root.AppendChild(element);

            //let's add another element (child of the root)
            element = xml.CreateElement("useHealthStone");
            text    = xml.CreateTextNode(useHealthStone.ToString());
            element.AppendChild(text);
            root.AppendChild(element);

            //let's add another element (child of the root)
            element = xml.CreateElement("useSoulstone");
            text    = xml.CreateTextNode(useSoulstone.ToString());
            element.AppendChild(text);
            root.AppendChild(element);

            //let's add another element (child of the root)
            element = xml.CreateElement("useDrainSoul");
            text    = xml.CreateTextNode(useDrainSoul.ToString());
            element.AppendChild(text);
            root.AppendChild(element);

            //let's add another element (child of the root)
            element = xml.CreateElement("useMetamorphosis");
            text    = xml.CreateTextNode(useMetamorphosis.ToString());
            element.AppendChild(text);
            root.AppendChild(element);

            //let's add another element (child of the root)
            element = xml.CreateElement("metamorphosisMinimumAggros");
            text    = xml.CreateTextNode(metamorphosisMinimumAggros.ToString());
            element.AppendChild(text);
            root.AppendChild(element);

            //let's add another element (child of the root)
            element = xml.CreateElement("useShadowCleave");
            text    = xml.CreateTextNode(useShadowCleave.ToString());
            element.AppendChild(text);
            root.AppendChild(element);

            //let's add another element (child of the root)
            element = xml.CreateElement("useImmolationAura");
            text    = xml.CreateTextNode(useImmolationAura.ToString());
            element.AppendChild(text);
            root.AppendChild(element);

            //let's add another element (child of the root)
            element = xml.CreateElement("useShadowFlame");
            text    = xml.CreateTextNode(useShadowFlame.ToString());
            element.AppendChild(text);
            root.AppendChild(element);

            //let's add another element (child of the root)
            element = xml.CreateElement("myLag");
            text    = xml.CreateTextNode(myLag.ToString());
            element.AppendChild(text);
            root.AppendChild(element);

            //let's add another element (child of the root)
            element = xml.CreateElement("petAttackDelay");
            text    = xml.CreateTextNode(petAttackDelay.ToString());
            element.AppendChild(text);
            root.AppendChild(element);

            //let's add another element (child of the root)
            element = xml.CreateElement("useArmor");
            text    = xml.CreateTextNode(useArmor.ToString());
            element.AppendChild(text);
            root.AppendChild(element);

            //let's add another element (child of the root)
            element = xml.CreateElement("armorName");
            text    = xml.CreateTextNode(armorName.ToString());
            element.AppendChild(text);
            root.AppendChild(element);

            //let's add another element (child of the root)
            element = xml.CreateElement("useShadowBolt");
            text    = xml.CreateTextNode(useShadowBolt.ToString());
            element.AppendChild(text);
            root.AppendChild(element);

            //let's add another element (child of the root)
            element = xml.CreateElement("useSoulFire");
            text    = xml.CreateTextNode(useSoulFire.ToString());
            element.AppendChild(text);
            root.AppendChild(element);

            //let's add another element (child of the root)
            element = xml.CreateElement("useIncinerate");
            text    = xml.CreateTextNode(useIncinerate.ToString());
            element.AppendChild(text);
            root.AppendChild(element);

            //let's add another element (child of the root)
            element = xml.CreateElement("useWand");
            text    = xml.CreateTextNode(useWand.ToString());
            element.AppendChild(text);
            root.AppendChild(element);

            //let's add another element (child of the root)
            element = xml.CreateElement("useSearingOfPain");
            text    = xml.CreateTextNode(useSearingOfPain.ToString());
            element.AppendChild(text);
            root.AppendChild(element);

            //let's add another element (child of the root)
            element = xml.CreateElement("useImmolate");
            text    = xml.CreateTextNode(useImmolate.ToString());
            element.AppendChild(text);
            root.AppendChild(element);

            //let's add another element (child of the root)
            element = xml.CreateElement("useCorruption");
            text    = xml.CreateTextNode(useCorruption.ToString());
            element.AppendChild(text);
            root.AppendChild(element);

            //let's add another element (child of the root)
            element = xml.CreateElement("dotAdds");
            text    = xml.CreateTextNode(dotAdds.ToString());
            element.AppendChild(text);
            root.AppendChild(element);

            //let's add another element (child of the root)
            element = xml.CreateElement("useCurse");
            text    = xml.CreateTextNode(useCurse.ToString());
            element.AppendChild(text);
            root.AppendChild(element);

            //let's add another element (child of the root)
            element = xml.CreateElement("curseName");
            text    = xml.CreateTextNode(curseName.ToString());
            element.AppendChild(text);
            root.AppendChild(element);

            //let's add another element (child of the root)
            element = xml.CreateElement("useLifeTap");
            text    = xml.CreateTextNode(useLifeTap.ToString());
            element.AppendChild(text);
            root.AppendChild(element);

            //let's add another element (child of the root)
            element = xml.CreateElement("lfTapMinHealth");
            text    = xml.CreateTextNode(lfTapMinHealth.ToString());
            element.AppendChild(text);
            root.AppendChild(element);

            //let's add another element (child of the root)
            element = xml.CreateElement("lfTapMaxMana");
            text    = xml.CreateTextNode(lfTapMaxMana.ToString());
            element.AppendChild(text);
            root.AppendChild(element);

            //let's add another element (child of the root)
            element = xml.CreateElement("useDrainLife");
            text    = xml.CreateTextNode(useDrainLife.ToString());
            element.AppendChild(text);
            root.AppendChild(element);

            //let's add another element (child of the root)
            element = xml.CreateElement("drainLifeMaxHealth");
            text    = xml.CreateTextNode(drainLifeMaxHealth.ToString());
            element.AppendChild(text);
            root.AppendChild(element);

            //let's add another element (child of the root)
            element = xml.CreateElement("drainLifeStopHealth");
            text    = xml.CreateTextNode(drainLifeStopHealth.ToString());
            element.AppendChild(text);
            root.AppendChild(element);

            //let's add another element (child of the root)
            element = xml.CreateElement("useDrainMana");
            text    = xml.CreateTextNode(useDrainMana.ToString());
            element.AppendChild(text);
            root.AppendChild(element);

            //let's add another element (child of the root)
            element = xml.CreateElement("useDeathCoil");
            text    = xml.CreateTextNode(useDeathCoil.ToString());
            element.AppendChild(text);
            root.AppendChild(element);

            //let's add another element (child of the root)
            element = xml.CreateElement("dcMaxHealth");
            text    = xml.CreateTextNode(dcMaxHealth.ToString());
            element.AppendChild(text);
            root.AppendChild(element);

            //let's add another element (child of the root)
            element = xml.CreateElement("useHealthFunnel");
            text    = xml.CreateTextNode(useHealthFunnel.ToString());
            element.AppendChild(text);
            root.AppendChild(element);

            //let's add another element (child of the root)
            element = xml.CreateElement("hfMinPlayerHealth");
            text    = xml.CreateTextNode(hfMinPlayerHealth.ToString());
            element.AppendChild(text);
            root.AppendChild(element);

            //let's add another element (child of the root)
            element = xml.CreateElement("hfPetMinHealth");
            text    = xml.CreateTextNode(hfPetMinHealth.ToString());
            element.AppendChild(text);
            root.AppendChild(element);

            //let's add another element (child of the root)
            element = xml.CreateElement("hfPetMaxHealth");
            text    = xml.CreateTextNode(hfPetMaxHealth.ToString());
            element.AppendChild(text);
            root.AppendChild(element);

            //let's add another element (child of the root)
            element = xml.CreateElement("useFear");
            text    = xml.CreateTextNode(useFear.ToString());
            element.AppendChild(text);
            root.AppendChild(element);

            //let's add another element (child of the root)
            element = xml.CreateElement("useHowlOfTerror");
            text    = xml.CreateTextNode(useHowlOfTerror.ToString());
            element.AppendChild(text);
            root.AppendChild(element);

            //let's add another element (child of the root)
            element = xml.CreateElement("useHaunt");
            text    = xml.CreateTextNode(useHaunt.ToString());
            element.AppendChild(text);
            root.AppendChild(element);

            //let's add another element (child of the root)
            element = xml.CreateElement("useUnstableAffliction");
            text    = xml.CreateTextNode(useUnstableAffliction.ToString());
            element.AppendChild(text);
            root.AppendChild(element);

            //let's add another element (child of the root)
            element = xml.CreateElement("useSummon");
            text    = xml.CreateTextNode(useSummon.ToString());
            element.AppendChild(text);
            root.AppendChild(element);

            //let's add another element (child of the root)
            element = xml.CreateElement("summonEntry");
            text    = xml.CreateTextNode(summonEntry.ToString());
            element.AppendChild(text);
            root.AppendChild(element);

            //let's add another element (child of the root)
            element = xml.CreateElement("useFelDomination");
            text    = xml.CreateTextNode(useFelDomination.ToString());
            element.AppendChild(text);
            root.AppendChild(element);

            //let's add another element (child of the root)
            element = xml.CreateElement("useEnslaveDemon");
            text    = xml.CreateTextNode(useEnslaveDemon.ToString());
            element.AppendChild(text);
            root.AppendChild(element);

            //let's add another element (child of the root)
            element = xml.CreateElement("useDemonicEmpowerment");
            text    = xml.CreateTextNode(useDemonicEmpowerment.ToString());
            element.AppendChild(text);
            root.AppendChild(element);

            //let's add another element (child of the root)
            element = xml.CreateElement("useDarkPact");
            text    = xml.CreateTextNode(useDarkPact.ToString());
            element.AppendChild(text);
            root.AppendChild(element);

            //let's add another element (child of the root)
            element = xml.CreateElement("useSoulLink");
            text    = xml.CreateTextNode(useSoulLink.ToString());
            element.AppendChild(text);
            root.AppendChild(element);


            xml.AppendChild(root);

            //let's try to save the XML document in a file: C:\pavel.xml
            System.IO.FileStream fs = new System.IO.FileStream(@sPath, System.IO.FileMode.Create, System.IO.FileAccess.Write);
            try
            {
                xml.Save(fs); //I've chosen the c:\ for the resulting file pavel.xml
                fs.Close();
            }
            catch (Exception e)
            {
                Logging.Write(e.Message);
            }
        }
コード例 #26
0
        private void New_Click(object sender, EventArgs e)
        {
            label.Hide();

            //创建XML文档
            doc = new XmlDocument();
            XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "UTF-8", "no");

            doc.AppendChild(dec);

            //创建根结点
            XmlElement scappleDocument = doc.CreateElement("ScappleDocument");

            doc.AppendChild(scappleDocument);

            XmlElement notes = doc.CreateElement("Notes");

            scappleDocument.AppendChild(notes);
            XmlElement backgroundShapes = doc.CreateElement("BackgroundShapes");

            scappleDocument.AppendChild(backgroundShapes);

            XmlElement noteStyles = doc.CreateElement("NoteStyles");

            //style1
            XmlElement style1 = doc.CreateElement("Style");

            style1.SetAttribute("AffectFontStyle", "No");
            style1.SetAttribute("AffectAlignment", "No");
            style1.SetAttribute("Name", "Brown Bubble");
            style1.SetAttribute("ID", "F780D2BA-F2C6-4507-829C-2D475F0F90EB");
            style1.SetAttribute("AffectTextColor", "No");
            style1.SetAttribute("AffectNoteBody", "Yes");
            style1.SetAttribute("AffectSticky", "No");
            style1.SetAttribute("AffectSize", "No");
            style1.SetAttribute("AffectFade", "No");

            XmlElement borderThickness1 = doc.CreateElement("BorderThickness");

            borderThickness1.InnerText = "1";
            style1.AppendChild(borderThickness1);
            XmlElement borderColor1 = doc.CreateElement("BorderColor");

            borderColor1.InnerText = "0.269490 0.164034 0.186694";
            style1.AppendChild(borderColor1);
            XmlElement fillColor1 = doc.CreateElement("FillColor");

            fillColor1.InnerText = "0.934157 0.888319 0.785290";
            style1.AppendChild(fillColor1);

            noteStyles.AppendChild(style1);

            //style2
            XmlElement style2 = doc.CreateElement("Style");

            style2.SetAttribute("AffectFontStyle", "No");
            style2.SetAttribute("AffectAlignment", "No");
            style2.SetAttribute("Name", "Green Bubble");
            style2.SetAttribute("ID", "4D8F6A13-FF36-47F6-BE62-12A67B42A484");
            style2.SetAttribute("AffectTextColor", "No");
            style2.SetAttribute("AffectNoteBody", "Yes");
            style2.SetAttribute("AffectSticky", "No");
            style2.SetAttribute("AffectSize", "No");
            style2.SetAttribute("AffectFade", "No");

            XmlElement borderThickness2 = doc.CreateElement("BorderThickness");

            borderThickness2.InnerText = "1";
            style2.AppendChild(borderThickness2);
            XmlElement borderColor2 = doc.CreateElement("BorderColor");

            borderColor2.InnerText = "0.399100 0.583322 0.354864";
            style2.AppendChild(borderColor2);
            XmlElement fillColor2 = doc.CreateElement("FillColor");

            fillColor2.InnerText = "0.808835 0.872419 0.801343";
            style2.AppendChild(fillColor2);

            noteStyles.AppendChild(style2);

            //style3
            XmlElement style3 = doc.CreateElement("Style");

            style3.SetAttribute("AffectFontStyle", "No");
            style3.SetAttribute("AffectAlignment", "No");
            style3.SetAttribute("Name", "Pink Bubble");
            style3.SetAttribute("ID", "E39A706D-0F10-4321-8D7C-9534420BBB99");
            style3.SetAttribute("AffectTextColor", "No");
            style3.SetAttribute("AffectNoteBody", "Yes");
            style3.SetAttribute("AffectSticky", "No");
            style3.SetAttribute("AffectSize", "No");
            style3.SetAttribute("AffectFade", "No");

            XmlElement borderThickness3 = doc.CreateElement("BorderThickness");

            borderThickness3.InnerText = "1";
            style3.AppendChild(borderThickness3);
            XmlElement borderColor3 = doc.CreateElement("BorderColor");

            borderColor3.InnerText = "0.690303 0.407263 0.550912";
            style3.AppendChild(borderColor3);
            XmlElement fillColor3 = doc.CreateElement("FillColor");

            fillColor3.InnerText = "0.898329 0.817472 0.865339";
            style3.AppendChild(fillColor3);

            noteStyles.AppendChild(style3);

            //style4
            XmlElement style4 = doc.CreateElement("Style");

            style4.SetAttribute("AffectFontStyle", "No");
            style4.SetAttribute("AffectAlignment", "No");
            style4.SetAttribute("Name", "Blue Bubble");
            style4.SetAttribute("ID", "4B2F8D04-9780-4FF0-96A2-E40E82F4453F");
            style4.SetAttribute("AffectTextColor", "No");
            style4.SetAttribute("AffectNoteBody", "Yes");
            style4.SetAttribute("AffectSticky", "No");
            style4.SetAttribute("AffectSize", "No");
            style4.SetAttribute("AffectFade", "No");

            XmlElement borderThickness4 = doc.CreateElement("BorderThickness");

            borderThickness4.InnerText = "1";
            style4.AppendChild(borderThickness4);
            XmlElement borderColor4 = doc.CreateElement("BorderColor");

            borderColor4.InnerText = "0.485893 0.568933 0.756207";
            style4.AppendChild(borderColor4);
            XmlElement fillColor4 = doc.CreateElement("FillColor");

            fillColor4.InnerText = "0.844068 0.869596 0.923064";
            style4.AppendChild(fillColor4);

            noteStyles.AppendChild(style4);

            //style5
            XmlElement style5 = doc.CreateElement("Style");

            style5.SetAttribute("AffectFontStyle", "Yes");
            style5.SetAttribute("AffectAlignment", "Yes");
            style5.SetAttribute("Name", "Title Text");
            style5.SetAttribute("ID", "DD5C481A-6ADF-4F13-B6D9-6C743262BA39");
            style5.SetAttribute("AffectTextColor", "No");
            style5.SetAttribute("AffectNoteBody", "No");
            style5.SetAttribute("AffectSticky", "No");
            style5.SetAttribute("AffectSize", "No");
            style5.SetAttribute("AffectFade", "No");

            XmlElement isBold = doc.CreateElement("IsBold");

            isBold.InnerText = "Yes";
            style5.AppendChild(isBold);
            XmlElement fontSize = doc.CreateElement("FontSize");

            fontSize.InnerText = "12.0";
            style5.AppendChild(fontSize);

            noteStyles.AppendChild(style5);

            //style6
            XmlElement style6 = doc.CreateElement("Style");

            style6.SetAttribute("AffectFontStyle", "No");
            style6.SetAttribute("AffectAlignment", "No");
            style6.SetAttribute("Name", "Red Text");
            style6.SetAttribute("ID", "21A0294F-5BFE-4B05-86CE-55829FF709B1");
            style6.SetAttribute("AffectTextColor", "Yes");
            style6.SetAttribute("AffectNoteBody", "No");
            style6.SetAttribute("AffectSticky", "No");
            style6.SetAttribute("AffectSize", "No");
            style6.SetAttribute("AffectFade", "No");

            XmlElement textColor = doc.CreateElement("TextColor");

            textColor.InnerText = "1.0 0.0 0.0";
            style6.AppendChild(textColor);

            noteStyles.AppendChild(style6);

            //style7
            XmlElement style7 = doc.CreateElement("Style");

            style7.SetAttribute("AffectFontStyle", "No");
            style7.SetAttribute("AffectAlignment", "No");
            style7.SetAttribute("Name", "Yellow Bubble");
            style7.SetAttribute("ID", "1B254D45-C971-4054-AE33-706BF3F4DAD5");
            style7.SetAttribute("AffectTextColor", "No");
            style7.SetAttribute("AffectNoteBody", "Yes");
            style7.SetAttribute("AffectSticky", "No");
            style7.SetAttribute("AffectSize", "No");
            style7.SetAttribute("AffectFade", "No");

            XmlElement borderThickness7 = doc.CreateElement("BorderThickness");

            borderThickness7.InnerText = "1";
            style7.AppendChild(borderThickness7);
            XmlElement borderColor7 = doc.CreateElement("BorderColor");

            borderColor7.InnerText = "0.769436 0.762219 0.390143";
            style7.AppendChild(borderColor7);
            XmlElement fillColor7 = doc.CreateElement("FillColor");

            fillColor7.InnerText = "0.912963 0.894118 0.644541";
            style7.AppendChild(fillColor7);

            noteStyles.AppendChild(style7);

            scappleDocument.AppendChild(noteStyles);


            XmlElement uiSettings      = doc.CreateElement("UISettings");
            XmlElement backgroundColor = doc.CreateElement("BackgroundColor");

            backgroundColor.InnerText = "1.0 0.988006 0.945006";
            XmlElement defaultFont = doc.CreateElement("DefaultFont");

            defaultFont.InnerText = "Helvetica";
            XmlElement defaultTextColor = doc.CreateElement("DefaultTextColor");

            defaultTextColor.InnerText = "0.0 0.0 0.0";

            uiSettings.AppendChild(backgroundColor);
            uiSettings.AppendChild(defaultFont);
            uiSettings.AppendChild(defaultTextColor);
            scappleDocument.AppendChild(uiSettings);

            XmlElement printSettings = doc.CreateElement("PrintSettings");

            printSettings.SetAttribute("VerticalPagination", "Auto");
            printSettings.SetAttribute("HorizontalPagination", "Clip");
            printSettings.SetAttribute("Orientation", "Portrait");
            printSettings.SetAttribute("RightMargin", "12.000000");
            printSettings.SetAttribute("BottomMargin", "12.000000");
            printSettings.SetAttribute("HorizontallyCentered", "Yes");
            printSettings.SetAttribute("ScaleFactor", "1.000000");
            printSettings.SetAttribute("PagesAcross", "1");
            printSettings.SetAttribute("PaperType", "iso-a4");
            printSettings.SetAttribute("PagesDown", "1");
            printSettings.SetAttribute("TopMargin", "12.000000");
            printSettings.SetAttribute("Collates", "Yes");
            printSettings.SetAttribute("PaperSize", "-1.000000,-1.000000");
            printSettings.SetAttribute("LeftMargin", "12.000000");
            printSettings.SetAttribute("VerticallyCentered", "Yes");

            scappleDocument.AppendChild(printSettings);
        }
コード例 #27
0
ファイル: Storage.cs プロジェクト: jn7163/airvpn-client
        public void Save()
        {
            string path = GetPath(Get("profile") + ".xml");

            bool remember = GetBool("remember");

            lock (this)
            {
                XmlDocument    xmlDoc         = new XmlDocument();
                XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null);

                XmlElement rootNode = xmlDoc.CreateElement("eddie");
                xmlDoc.InsertBefore(xmlDeclaration, xmlDoc.DocumentElement);

                XmlElement optionsNode = xmlDoc.CreateElement("options");
                rootNode.AppendChild(optionsNode);

                xmlDoc.AppendChild(rootNode);

                foreach (Option option in Options.Values)
                {
                    bool skip = false;

                    if ((remember == false) && (option.Code == "login"))
                    {
                        skip = true;
                    }
                    if ((remember == false) && (option.Code == "password"))
                    {
                        skip = true;
                    }

                    if (option.CommandLineOnly)
                    {
                        skip = true;
                    }

                    if ((option.Value == "") || (option.Value == option.Default))
                    {
                        skip = true;
                    }

                    if (skip == false)
                    {
                        XmlElement itemNode = xmlDoc.CreateElement("option");
                        itemNode.SetAttribute("name", option.Code);
                        itemNode.SetAttribute("value", option.Value);
                        optionsNode.AppendChild(itemNode);
                    }
                }


                XmlElement providersNode = xmlDoc.CreateElement("providers");
                rootNode.AppendChild(providersNode);
                foreach (Provider provider in Engine.Instance.ProvidersManager.Providers)
                {
                    XmlNode providerNode = xmlDoc.ImportNode(provider.Storage.DocumentElement, true);
                    providersNode.AppendChild(providerNode);
                }

                if (Engine.Instance.ProvidersManager.Providers.Count == 1)
                {
                    if (Engine.Instance.ProvidersManager.Providers[0].GetCode() == "AirVPN")
                    {
                        // Move providers->AirVPN to root.
                        XmlElement xmlAirVPN = Utils.XmlGetFirstElementByTagName(providersNode, "AirVPN");
                        if (xmlAirVPN != null)
                        {
                            foreach (XmlElement xmlChild in xmlAirVPN.ChildNodes)
                            {
                                Utils.XmlCopyElement(xmlChild, xmlDoc.DocumentElement);
                            }
                            providersNode.RemoveChild(xmlAirVPN);
                        }
                        if (providersNode.ChildNodes.Count == 0)
                        {
                            providersNode.ParentNode.RemoveChild(providersNode);
                        }
                    }
                }

                xmlDoc.Save(path);
            }

            if (Platform.Instance.IsUnixSystem())
            {
                Platform.Instance.ShellCmd("chmod 600 \"" + path + "\"");
            }
        }
コード例 #28
0
        public void saveGameXML(String xmlfile)
        {
            XmlDocument xml   = new XmlDocument();
            XmlElement  root  = xml.CreateElement("xml");
            XmlElement  games = xml.CreateElement("games");

            xml.AppendChild(root);
            root.AppendChild(games);

            foreach (Game g in GameList)
            {
                XmlElement game = xml.CreateElement("game");
                games.AppendChild(game);
                foreach (KeyValuePair <String, Param> entry in g.Params)
                {
                    if (entry.Value.value.value != "")
                    {
                        XmlElement e = xml.CreateElement("param");
                        e.SetAttribute(entry.Value.name.key, entry.Value.name.value);
                        e.SetAttribute(entry.Value.value.key, entry.Value.value.value);
                        e.SetAttribute(entry.Value.desc.key, entry.Value.desc.value);
                        game.AppendChild(e);
                    }
                }
                if (g.Logs.Count > 0)
                {
                    XmlElement log = xml.CreateElement("log");
                    game.AppendChild(log);
                    foreach (KeyValuePair <String, Param> entry in g.Logs)
                    {
                        if (entry.Value.value.value != "")
                        {
                            XmlElement e = xml.CreateElement("param");
                            e.SetAttribute(entry.Value.name.key, entry.Value.name.value);
                            e.SetAttribute(entry.Value.value.key, entry.Value.value.value);
                            e.SetAttribute(entry.Value.desc.key, entry.Value.desc.value);
                            log.AppendChild(e);
                        }
                    }
                }

                try
                {
                    String dest = g.Params["appName"].value.value;
                    if (g.AppName != dest && dest != "")
                    {
                        String source = g.AppName;
                        g.AppName = dest;
                        Directory.Move(ProjectConfig.getInstance().getGameList() + source, ProjectConfig.getInstance().getGameList() + dest);
                    }
                }
                catch (System.Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }

            XmlDeclaration xmldecl = xml.CreateXmlDeclaration("1.0", "UTF-8", null);

            xml.InsertBefore(xmldecl, root);
            xml.Save(xmlfile);
        }
コード例 #29
0
ファイル: CXml.cs プロジェクト: legoli/Diancan
        public bool generateConfigFile()
        {
            //判断文件是否已经存在
            if (System.IO.File.Exists(this.xmlFileName))
            {
                Console.WriteLine(String.Format("文件{0}已经存在", this.xmlFileName));
                //return false;
            }

            XmlDocument xmldoc = new XmlDocument();
            //加入XML的声明段落,<?xml version="1.0" encoding="gb2312"?>
            XmlDeclaration decl = xmldoc.CreateXmlDeclaration("1.0", "gb2312", null);

            xmldoc.AppendChild(decl);

            XmlElement element = null;

            //加入一个根元素
            //element = xmldoc.CreateElement("prifix", "localName", "namespaceURI");
            element = xmldoc.CreateElement("root");
            xmldoc.AppendChild(element);

            //取得要加入的Parent节点
            XmlNode root = xmldoc.SelectSingleNode("root");

            //系统配置参数设置-------------------------------------------------------------
            XmlElement nParams = xmldoc.CreateElement("system_params");

            nParams.SetAttribute("type", "系统参数");

            XmlElement item = xmldoc.CreateElement("item"); //创建一个item节点

            item.SetAttribute("name", "tj_db");             //设置item节点属性
            item.SetAttribute("value", "192.168.1.209");    //设置item节点属性
            item.SetAttribute("tip", "体检服务器IP");            //设置item节点属性
            nParams.AppendChild(item);

            item = xmldoc.CreateElement("item");                    //创建一个item节点
            item.SetAttribute("name", "form_location");             //设置item节点属性
            item.SetAttribute("value", "full");                     //设置item节点属性
            item.SetAttribute("tip", "程序显示位置,可选项:left/right/full"); //设置item节点属性
            nParams.AppendChild(item);

            item = xmldoc.CreateElement("item");       //创建一个item节点
            item.SetAttribute("name", "room_id");      //设置item节点属性
            item.SetAttribute("value", "[322]");       //设置item节点属性
            item.SetAttribute("tip", "检查室编号:格式[322]"); //设置item节点属性
            nParams.AppendChild(item);

            item = xmldoc.CreateElement("item");    //创建一个item节点
            item.SetAttribute("name", "room_name"); //设置item节点属性
            item.SetAttribute("value", "322室");     //设置item节点属性
            item.SetAttribute("tip", "检查室名称,用于显示"); //设置item节点属性
            nParams.AppendChild(item);

            item = xmldoc.CreateElement("item");         //创建一个item节点
            item.SetAttribute("name", "site_id");        //设置item节点属性
            item.SetAttribute("value", "三二二室 ");         //设置item节点属性
            item.SetAttribute("tip", "进程ID,用于语音叫号的房间号"); //设置item节点属性
            nParams.AppendChild(item);

            item = xmldoc.CreateElement("item");     //创建一个item节点
            item.SetAttribute("name", "tts_ip");     //设置item节点属性
            item.SetAttribute("value", "127.0.0.1"); //设置item节点属性
            item.SetAttribute("tip", "语音等级台IP地址");   //设置item节点属性
            nParams.AppendChild(item);

            item = xmldoc.CreateElement("item");                 //创建一个item节点
            item.SetAttribute("name", "apply_sheet_position");   //设置item节点属性
            item.SetAttribute("value", "0");                     //设置item节点属性
            item.SetAttribute("tip", "申请单显示的默认页面位置,范围(0 ~ 10)"); //设置item节点属性
            nParams.AppendChild(item);

            //加入到root
            root.AppendChild(nParams);

            //插队原因列表-----------------------------------------------------------------
            XmlElement queueOrderChangeReason = xmldoc.CreateElement("queue_order_change_reason");

            queueOrderChangeReason.SetAttribute("type", "插队原因");

            item = xmldoc.CreateElement("item"); //创建一个item节点
            item.SetAttribute("name", "发热");     //设置item节点属性
            queueOrderChangeReason.AppendChild(item);

            item = xmldoc.CreateElement("item"); //创建一个item节点
            item.SetAttribute("name", "急诊");     //设置item节点属性
            queueOrderChangeReason.AppendChild(item);

            item = xmldoc.CreateElement("item"); //创建一个item节点
            item.SetAttribute("name", "军人");     //设置item节点属性
            queueOrderChangeReason.AppendChild(item);

            //加入到root
            root.AppendChild(queueOrderChangeReason);


            //保存为磁盘文件
            xmldoc.Save(this.xmlFileName);

            return(true);
        }
コード例 #30
0
        public static void DoReplaceInFile(string file, ReplaceSettings settings, SDLXLIFFSliceOrChange sdlxliffSliceOrChange)
        {
            try
            {
                sdlxliffSliceOrChange.StepProcess("Replaceing in file: " + file + "...");

                String fileContent = String.Empty;
                using (StreamReader sr = new StreamReader(file))
                {
                    fileContent = sr.ReadToEnd();
                }
                fileContent = Regex.Replace(fileContent, "\t", "");

                using (StreamWriter sw = new StreamWriter(file, false))
                {
                    sw.Write(fileContent);
                }

                XmlDocument xDoc = new XmlDocument();
                xDoc.PreserveWhitespace = true;
                xDoc.Load(file);

                String xmlEncoding = "utf-8";
                try
                {
                    if (xDoc.FirstChild.NodeType == XmlNodeType.XmlDeclaration)
                    {
                        // Get the encoding declaration.
                        XmlDeclaration decl = (XmlDeclaration)xDoc.FirstChild;
                        xmlEncoding = decl.Encoding;
                    }
                }
                catch (Exception ex)
                {
                    logger.Error(ex.Message, ex);
                }

                XmlNodeList fileList = xDoc.DocumentElement.GetElementsByTagName("file");
                foreach (XmlElement fileElement in fileList.OfType <XmlElement>())
                {
                    XmlElement  bodyElement   = (XmlElement)(fileElement.GetElementsByTagName("body")[0]);
                    XmlNodeList groupElements = bodyElement.GetElementsByTagName("group");

                    foreach (var groupElement in groupElements.OfType <XmlElement>())
                    {
                        //look in segments
                        XmlNodeList transUnits = ((XmlElement)groupElement).GetElementsByTagName("trans-unit");
                        foreach (XmlElement transUnit in transUnits.OfType <XmlElement>())
                        {
                            XmlNodeList source = transUnit.GetElementsByTagName("source");
                            if (source.Count > 0) //in mrk, g si innertext
                            {
                                ReplaceAllChildsValue((XmlElement)source[0], settings);
                            }
                            source = null;
                            XmlNodeList segSource = transUnit.GetElementsByTagName("seg-source");
                            if (segSource.Count > 0) //in mrk, g si innertext
                            {
                                ReplaceAllChildsValue((XmlElement)segSource[0], settings);
                            }
                            segSource = null;
                            XmlNodeList target = transUnit.GetElementsByTagName("target");
                            if (target.Count > 0) //in mrk, g si innertext
                            {
                                ReplaceAllChildsValue((XmlElement)target[0], settings, false);
                            }
                            target = null;
                        }
                    }

                    //look in segments not located in groups
                    XmlNodeList transUnitsInBody = bodyElement.ChildNodes;//.GetElementsByTagName("trans-unit");
                    foreach (XmlElement transUnit in transUnitsInBody.OfType <XmlElement>())
                    {
                        if (transUnit.Name != "trans-unit")
                        {
                            continue;
                        }
                        XmlNodeList source = transUnit.GetElementsByTagName("source");
                        if (source.Count > 0) //in mrk, g si innertext
                        {
                            ReplaceAllChildsValue((XmlElement)source[0], settings);
                        }
                        source = null;
                        XmlNodeList segSource = transUnit.GetElementsByTagName("seg-source");
                        if (segSource.Count > 0) //in mrk, g si innertext
                        {
                            ReplaceAllChildsValue((XmlElement)segSource[0], settings);
                        }
                        segSource = null;
                        XmlNodeList target = transUnit.GetElementsByTagName("target");
                        if (target.Count > 0) //in mrk, g si innertext
                        {
                            ReplaceAllChildsValue((XmlElement)target[0], settings, false);
                        }
                        target = null;
                    }

                    bodyElement      = null;
                    groupElements    = null;
                    transUnitsInBody = null;
                }
                Encoding encoding = new UTF8Encoding();
                if (!String.IsNullOrEmpty(xmlEncoding))
                {
                    encoding = Encoding.GetEncoding(xmlEncoding);
                }

                using (var writer = new XmlTextWriter(file, encoding))
                {
                    ////writer.Formatting = Formatting.None;
                    xDoc.Save(writer);
                }

                fileContent = String.Empty;
                using (StreamReader sr = new StreamReader(file))
                {
                    fileContent = sr.ReadToEnd();
                }
                fileContent = Regex.Replace(fileContent, "", "\t");

                using (StreamWriter sw = new StreamWriter(file, false))
                {
                    sw.Write(fileContent);
                }

                xDoc     = null;
                fileList = null;
                sdlxliffSliceOrChange.StepProcess("All information replaced in file: " + file + ".");
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message, ex);
            }
        }