C#XML操作

1、元素和特性的区别:可以给元素添加子元素或特性,而对特性不可以;未经压缩就在网络上传输文档,则特性占用更少的带宽。
2、VS中XML的声明只支持1.0版本:<?xml version = "1.0"?>
3、命名空间:xmlns:namespace1 = ""
4、验证XML文档常用模式而不是文档类型定义(DTD)。其中常用模式格式是XSD而不是XDR。
 注:XSD模式中的元素必须属于名称空间:http://www.w3.org/2001/XMLSchema;否则,就不能识别这些模式元素。
5、跟元素是使用XmlDocument类的属性DocumentElement获得的。
6、递归显示XML文档内容:

 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)
      {
        AddAttributes(node, ref text);
      }
      if (node.HasChildNodes)
      {
        text += ">";
        foreach (XmlNode child in node.ChildNodes)
        {
          text = FormatText(child, text, indent + "  ");
        }
        if (node.ChildNodes.Count == 1 &&
           (node.FirstChild is XmlText || node.FirstChild is XmlComment))
          text += "</" + node.Name + ">";
        else
          text += "
" + indent + "</" + node.Name + ">";
      }
      else
        text += " />";
      return text;
    }

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

  注:节点的子节点未必是XMLNode,还可能是XmlText或XmlComment;CreateTextNode可以创建XmlText。
7、XmlNode类包含两个方法(SelectSingleNode和SelectNodes)常用于从文档中选择节点,且不遍历其中的每个节点,它们都使用一种特殊的查询语言XPath来选择节点。

原文地址:https://www.cnblogs.com/shenchao/p/4558944.html