在C#中使用XML指南:读取XML
/// <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();
}
}
}
}