XML文档对象模型(Document Object Model,DOM)是一组已非常直观的方式访问和处理XML的类。位于System.Xml中
XmlNode:XML文档中的一个节点
获取节点值:
InnerText:获取节点中的文本
InnerXml:返回字节的及内容
Value:XmlText,XmlComment,XmlAttribute会返回Value值
创建节点:
CreateNode:创建任意类型节点
CreateElement:创建XmlElement类型的节点
CreateAttribute:创建XMLAttribute类型
CreateTextNode:创建XMLTextNode类型节点
CreateComment:创建注释
插入节点:
AppendChild:添加子节点
InsertAfter:在参考节点之后插入新节点
InserBefore:在参考节点之前插入新节点
- //Xml对象
- XmlDocument document = new XmlDocument();
- document.Load(@"path\Books.xml");
- // 根节点
- XmlElement root = document.DocumentElement;
- //XmlElement类型 子节点
- XmlElement newBook = document.CreateElement("book");
- XmlElement newTitle = document.CreateElement("title");
- XmlElement newAuthor = document.CreateElement("author");
- XmlElement newCode = document.CreateElement("code");
- //XmlText类型 子节点
- XmlText title = document.CreateTextNode("Beginning Visual C#");
- XmlText author = document.CreateTextNode("Ben");
- XmlText code = document.CreateTextNode("314418");
- //注释
- XmlComment comment = document.CreateComment("The previous edition");
- // 添加子节点
- newBook.AppendChild(comment);
- newBook.AppendChild(newTitle);
- newBook.AppendChild(newAuthor);
- newBook.AppendChild(newCode);
- //添加<></>标记之间的text值
- newTitle.AppendChild(title);
- newAuthor.AppendChild(author);
- newCode.AppendChild(code);
- //添加位置,最后一个
- root.InsertAfter(newBook, root.LastChild);
- //保存
- document.Save(@"path\Books.xml");
选择节点:
SelectSingleNode:选择一个节点
SelectNodes:以XmlNodesList类的形式返回一个节点集合
删除节点:
RemoveAll:删除所有子节点
RemoveChild:删除一个子节点
- XmlNode book=root.LastChild;
- root.RemoveChild(book);
XmlDocument:XML文档对象
- XmlDocument document=new XmlDocument();
- document.Load("path\xxx.xml");
XmlElement:XML文档的一个元素
- XmlElement element=document.DocumentElement;
FirstChild:返回第一个子节点
LastChild:返回最后一个字节点
ParentNode:返回父节点
NextSibling:返回下个节点
HasChildNodes:检查当前元素是否有子元素
XmlAttribute:XML元素的属性 sex="female"
<author sex='female'>"Ben"</author>
XmlText:<></>标记之间的文本 Beginning Visual C#
<title>Beginning Visual C#</title>
XmlComment:XML文档的注释
<!--这个是注释-->
XmlNodeList:XML文档节点集合