simen-tan

用于操作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 += "\r\n" + 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 += "\r\n" + 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 + "\'";
            }
        }

  

分类:

技术点:

相关文章:

  • 2021-12-05
  • 2021-08-16
  • 2021-07-13
  • 2021-08-16
  • 2021-05-16
  • 2022-12-23
  • 2021-04-30
  • 2021-09-04
猜你喜欢
  • 2022-12-23
  • 2021-08-16
  • 2021-09-01
  • 2021-05-29
  • 2021-07-27
相关资源
相似解决方案