在应用程序中使用Xml文件

用于操作Xml的文档主要有XmlNode、XmlDocument、XmlComment、XmlElement、XmlAttribute、XmlText、XmlNodeList

下面用一段代码来具体说明怎么操作Xml文件的:

  private void button1_Click(object sender, EventArgs e)
        {
            XmlDocument document = new XmlDocument();
            document.Load("XmlReader");
            textBox1.Text = FormatText(document.DocumentElement as XmlNode, "", "");
        }

        private string FormatText(XmlNode node, string text, string indent)
        {
            if (node is XmlText)
            {
                text += node.Value;
                return text;
            }
            if (string.IsNullOrEmpty(indent))
            {
                indent = "";
            }
            else
            {
                text += "
" + indent;
            }
            if (node is XmlComment)
            {
                text += node.OuterXml;
                return text;
            }
            text += "<" + node.Name;
            if (node.Attributes.Count > 0)
            {
                AddAttribute(node, ref text);
            }
            if (node.HasChildNodes)
            {
                text += ">";
                foreach (XmlNode child in node.ChildNodes)
                {
                    FormatText(child, text, indent + " ");
                }
                if (node.ChildNodes.Count == 1 && (node.FirstChild is XmlText || node.FirstChild is XmlComment))
                {
                    text += "
" + indent + "</" + node.Name + ">";
                }
                
            }
            else
            {
                text += "/>";
            }
            return text;
        }

        private void AddAttribute(XmlNode node, ref string text)
        {
            foreach (XmlAttribute attribute in node.Attributes)
            {
                text += " " + attribute.Name + "='" + attribute.Value + "'";
            }
        }

  

原文地址:https://www.cnblogs.com/simen-tan/p/5389567.html