C#中用XmlDocument对象获取XML文件中的节点值
XmlDocument是表示DOM的类。1.加载XML文档:使用load()方法加载XML文档;
2.读取节点:使用GetElementById()、getElementsByTagName_r()方法根据ID或标签名读取节点;
3.查找节点:使用SelectSingleNode(string
4.插入节点:使用createElement_x()方法创建节点,AppendChild()方法添加新节点;
5.创建文档:通过XmlDeclaration对象新建声明节点,其他同插入节点。
xml文件:
<?xml version="1.0" encoding="utf-8" ?>
<bookstore>
</bookstore>
实例:处理books.xml文档
TestXmlDocument.cs:
001.
using
System;
002.
using
System.Xml;
003.
004.
namespace
Magci.Test.XML.TestXmlDocment
005.
{
006.
class
Program
007.
{
008.
private
static
XmlDocument doc;
009.
010.
static
void
Main(
string
[] args)
011.
{
012.
doc =
new
XmlDocument();
013.
//加载XML文档
014.
doc.Load(@
"..\..\books.xml"
);
015.
DisplayTitle();
016.
SearchByTitle(
"The Gorgias"
);
017.
Insert();
018.
CreateDoc();
019.
020.
Console.ReadLine();
021.
}
022.
023.
//遍历节点
024.
public
static
void
DisplayTitle()
025.
{
026.
XmlNodeList nodes = doc.getElementsByTagName_r(
"title"
);
027.
Console.WriteLine(
"Title:"
);
028.
foreach
(XmlNode node
in
nodes)
029.
{
030.
Console.WriteLine(node.InnerText);
031.
}
032.