ASP.NET----使用XmlDocument读写节点属性

上篇文章中提到XML转换问题,有些朋友颇有疑问,后期答复详解,这次带来使用XmlDocument读写节点属性

  
    
using System;
using System.Xml;
namespace NET.MST.Tenth.UseXmlDocument
{
partial class UseXmlDocument
{
static void Main( string [] args)
{
String path
= " ..\\..\\Test.xml " ;
XmlDocument xml
= new XmlDocument();
xml.Load(path);
Console.WriteLine(
" 原先的XML文档是: " );
PringDocument(xml);
Console.WriteLine(
" 新建了节点之后: " );
AddNode(xml);
PringDocument(xml);
Console.WriteLine(
" 修改了节点之后: " );
EditNode(xml);
PringDocument(xml);
Console.WriteLine(
" 删除了节点之后: " );
DeleteNode(xml);
PringDocument(xml);
Console.Read();
}
/// <summary>
/// 格式化输出XML文档
/// </summary>
/// <param name="xml"> 需要显示的文档 </param>
static void PringDocument(XmlDocument xml)
{
xml.Save(Console.Out);
Console.Write(
" \r\n " );
}
}
partial class UseXmlDocument
{
/// <summary>
/// 删除最后一个Book节点
/// </summary>
/// <param name="xml"></param>
static void DeleteNode(XmlDocument xml)
{
XmlNode node
= xml.DocumentElement;
XmlNode remove
= node.ChildNodes[node.ChildNodes.Count - 1 ];
remove.Attributes.RemoveAt(
0 );
node.RemoveChild(remove);
}
}
partial class UseXmlDocument
{
/// <summary>
/// 修改最后一个Book节点的节点值和属性
/// </summary>
/// <param name="xml"></param>
static void EditNode(XmlDocument xml)
{
XmlNode node
= xml.DocumentElement;
XmlNode editnode
= node.ChildNodes[node.ChildNodes.Count - 1 ];
editnode.Attributes[
" name " ].Value = " book4 " ;
editnode.SelectSingleNode(
" Auth " ).InnerText = " z4 " ;
editnode.SelectSingleNode(
" Date " ).InnerText = " 2008-1-4 " ;
}
}
partial class UseXmlDocument
{
/// <summary>
/// 增加节点、属性
/// </summary>
/// <param name="xml"> 被操作的XML文档 </param>
static void AddNode(XmlDocument xml)
{
// 新建新Book节点
XmlNode newnode = xml.CreateElement( " Book " );
// 新建name节点
XmlAttribute newattribute = xml.CreateAttribute( " name " );
newattribute.Value
= " book3 " ;
newnode.Attributes.Append((XmlAttribute)newattribute);
// 新建Auth节点
XmlNode auth = xml.CreateElement( " Auth " );
auth.InnerText
= " z3 " ;
// 新建Date节点
XmlNode date = xml.CreateElement( " Date " );
date.InnerText
= " 2008-1-3 " ;
// 添加所有新建的节点和属性
newnode.AppendChild(auth);
newnode.AppendChild(date);
xml.DocumentElement.AppendChild(newnode);
}
}
}

你可能感兴趣的:(document)