zoukankan      html  css  js  c++  java
  • C# WinForm 创建XML文件方法总结

    两种方法,看大家喜好选择吧:

    方法一:

    XmlDocument xmldoc = new XmlDocument();
    XmlText xmltext;

    //声明
    XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration, "", "");
    xmlnode.InnerText
    += " encoding=\"GB2312\"";
    xmldoc.AppendChild(xmlnode);

    //添加根节点
    XmlElement xmlelementroot = xmldoc.CreateElement("", "Config", "");
    //根节点包含节点文本时会造成XML文档结构的混乱
    //xmltext = xmldoc.CreateTextNode("配置信息");
    //xmlelementroot.AppendChild(xmltext);
    xmldoc.AppendChild(xmlelementroot);

    //添加一个元素
    XmlElement xmlelement1 = xmldoc.CreateElement("", "DTL", "");
    xmltext
    = xmldoc.CreateTextNode("2010-10-25");
    xmlelement1.AppendChild(xmltext);
    xmldoc.ChildNodes.Item(
    1).AppendChild(xmlelement1);

    //添加另一个元素
    XmlElement xmlelement2 = xmldoc.CreateElement("", "DTF", "");
    xmltext
    = xmldoc.CreateTextNode("2011-02-10");
    xmlelement2.AppendChild(xmltext);
    xmldoc.ChildNodes.Item(
    1).AppendChild(xmlelement2);

    //保存
    xmldoc.Save(getPath());

    方法二:

    XmlTextWriter xmlwriter = new XmlTextWriter(getPath(), Encoding.Default);
    xmlwriter.Formatting
    = Formatting.Indented;
    xmlwriter.Indentation
    = 4;

    xmlwriter.WriteStartDocument();
    xmlwriter.WriteStartElement(
    "", "Config", "");

    xmlwriter.WriteStartElement(
    "", "DTL", "");
    xmlwriter.WriteString(
    "2010-10-25");
    xmlwriter.WriteEndElement();

    xmlwriter.WriteStartElement(
    "", "DTF", "");
    xmlwriter.WriteString(
    "2011-02-10");
    xmlwriter.WriteEndElement();

    xmlwriter.WriteEndElement();
    xmlwriter.WriteEndDocument();

    xmlwriter.Flush();
    xmlwriter.Close();

    上面两段代码中的getPath()是自定义的一个获取文件路径加名称的方法,请根据自己实际情况修改!

    总的来说还是方法二比较容易理解,简单易用,也是我常用的方法!

    希望对各位有所帮助!

  • 相关阅读:
    ExecuteScalar requires the command to have a transaction when the connection assigned to the command is in a pending
    如何从vss中分离程序
    String or binary data would be truncated
    the pop3 service failed to retrieve authentication type and cannot continue
    The POP3 service failed to start because
    IIS Error he system cannot find the file specified _找不到页面
    pku2575Jolly Jumpers
    pku2940Wine Trading in Gergovia
    pku3219二项式系数
    pku1029false coin
  • 原文地址:https://www.cnblogs.com/mic86/p/1900131.html
Copyright © 2011-2022 走看看