在C#中使用XML指南:读取XML

来源:中国站长学院  作者:佚名
摘要:对于XML,想必各位都比较了解,我也就不用费笔墨来描述它是什么了,我想在未来的Web开发中XML一定会大放异彩,XML是可扩展标记语言,使用它企业可以制定一套自己的数据格式,数据按照这种格式在网络中传输然后再通过XSLT将数据转换成用户期望的样子表示出来,这样…

/// <summary>
  /// 读取Xml文件的命名空间
  /// </summary>
  public void ReadXmlNamespace()
  {
   this._listBox.Items.Clear();
   this.xmlTxtRd = new XmlTextReader(this._xmlPath);
   try
   {
    while(xmlTxtRd.Read())
    {
     if (xmlTxtRd.NodeType == XmlNodeType.Element && xmlTxtRd.Prefix != "")
     {
      this._listBox.Items.Add("The Prefix " + xmlTxtRd.Prefix + " is associated with namespace " + xmlTxtRd.NamespaceURI);

this._listBox.Items.Add("The Element with the local name " + xmlTxtRd.LocalName + " is associated with" + " the namespace " + xmlTxtRd.NamespaceURI);
     }

 if (xmlTxtRd.NodeType == XmlNodeType.Element && xmlTxtRd.HasAttributes)
     {
      while(xmlTxtRd.MoveToNextAttribute())
      {
       if (xmlTxtRd.Prefix != "")
       {
        this._listBox.Items.Add("The Prefix " + xmlTxtRd.Prefix + " is associated with namespace " + xmlTxtRd.NamespaceURI);

this._listBox.Items.Add("The Attribute with the local name " + xmlTxtRd.LocalName + " is associated with the namespace " + xmlTxtRd.NamespaceURI);

 }
      }
     }
    }
   }
   catch(XmlException xmlExp)
   {
    throw new XmlException(_errMsg + this._xmlPath + xmlExp.ToString());
   }
   finally
   {
    if (this.xmlTxtRd != null)
     this.xmlTxtRd.Close();
   }
  }

/// <summary>
  /// 读取整个Xml文件
  /// </summary>
  public void ReadXml()
  {
   string attAndEle = string.Empty;
   this._listBox.Items.Clear();
   this.xmlTxtRd = new XmlTextReader(this._xmlPath);

 try
   {
    while(xmlTxtRd.Read())
    {
     if (xmlTxtRd.NodeType == XmlNodeType.XmlDeclaration)
      this._listBox.Items.Add(string.Format("<?{0} {1} ?>",xmlTxtRd.Name,xmlTxtRd.Value));
     else if (xmlTxtRd.NodeType == XmlNodeType.Element)
     {
      attAndEle = string.Format("<{0} ",xmlTxtRd.Name);
      if (xmlTxtRd.HasAttributes)
      {
       while(xmlTxtRd.MoveToNextAttribute())
       {
        attAndEle = attAndEle + string.Format("{0}='{1}' ",xmlTxtRd.Name,xmlTxtRd.Value);
       }
      }

attAndEle = attAndEle.Trim() + ">";
      this._listBox.Items.Add(attAndEle);
     }
     else if (xmlTxtRd.NodeType == XmlNodeType.EndElement)
      this._listBox.Items.Add(string.Format("</{0}>",xmlTxtRd.Name));
     else if (xmlTxtRd.NodeType == XmlNodeType.Text)
      this._listBox.Items.Add(xmlTxtRd.Value);
    }
   }
   catch(XmlException xmlExp)
   {
    throw new XmlException(_errMsg + this._xmlPath + xmlExp.ToString());
   }
   finally
   {
    if (this.xmlTxtRd != null)
     this.xmlTxtRd.Close();
   }
  }
 }
}

【相关文章】好搜一下
Windows Mobile程序的自动化测试简介

Windows Mobile程序的自动化测试

随手打开MEDC2007的课程列表页面,看到了一个课程的标题《使用Windows…