在.NET中操作XmlDocument

大家想必一定都了解XML,利用XML技术来存储数据和文档是一件很容易的事情,.NET Framework 在它的命名空间 System.Xml 就提供了一种可以很方便的操作xml的类 XmlDocument,它使用起来非常容易,XmlDocument 其实就是一个简单的树。下面详细的介绍XmlDocument 的使用方法。

下面是这个类中操作节点的常用方法。

// create a new node in the document object from the source node
//and name it as "sName"
// the return value indicates success or failure
public bool AddNode(XmlNode oSource, String sName);

// same as above except that it also specifies the parent node of the
// newly created node
// the return value indicates success or failure (returns false if the
// parent node does not exist)
public bool AddNode(XmlNode oSource, String sName, String sParent);

// create a set of new nodes in the document object from the source node
// list and name them as "sName"
// the return value indicates success or failure
public bool AddNodes(XmlNodeList oSourceList, String sName);

// same as above except that it also specifies the parent node of the
// newly created nodes the return value indicates success or failure
// (returns false if the parent node
// does not exist)
public bool AddNodes(XmlNodeList oSourceList, String sName, String sParent);

// merge the source node into a node named "sName" in the document object
// the node named "sName" will be created if it does not exist
// the return value indicates success or failure
public bool MergeNode(XmlNode oSource, String sName);

// same as above except that it also specifies the parent node of the merged node
// the return value indicates success or failure (returns false if the parent node
// does not exist)
public bool MergeNode(XmlNode oSource, String sName, String sParent);

下面我们给一个增加节点的例子

docVechile.xml

 1<vehicledata>
 2<record>
 3<id>1001</id>
 4<make>Ford</make>
 5<model>Escort</model>
 6<year>1984</year>
 7</record>
 8<record>
 9<id>1002</id>
10<make>Toyota</make>
11<model>Tercel</model>
12<year>1996</year>
13</record>
14<record>
15<id>1003</id>
16<make>Mazda</make>
17<model>GLC</model>
18<year>1985</year>
19</record>
20</vehicledata>

docDriver.xml

 1<driverdata>
 2<record>
 3<id>1</id>
 4<firstname>Albert</firstname>
 5<lastname>Einstein</lastname>
 6</record>
 7<record>
 8<id>2</id>
 9<firstname>Clint</firstname>
10<lastname>Eastwood</lastname>
11</record>
12<record>
13<id>3</id>
14<firstname>James</firstname>
15<lastname>Bond</lastname>
16</record>
17</driverdata>

下面的代码将增加一个节点:

Dim myDoc As XMLDocumentEx = New XMLDocumentEx()
myDoc.LoadXml("
1<data></data>

") myDoc.AddNode(docVehicle.SelectSingleNode("//Record"), "VehicleRecord", "Data") myDoc.AddNode(docDriver.SelectSingleNode("//Record"), "DriverRecord", "Data")

_myDoc.xml_
 1<data>
 2<vehiclerecord>
 3<id>...</id>
 4<make>...</make>
 5<model>...</model>
 6<year>...</year>
 7<!-- Vehicle Record-->
 8<driverrecord>
 9<id>...</id>
10<firstname>...</firstname>
11<lastname>...</lastname>
12</driverrecord>
13</vehiclerecord></data>

我们也可是使用AddNodes方法把一个记录集的所有记录增加到节点上:

Dim myDoc As XMLDocumentEx = New XMLDocumentEx()
myDoc.LoadXml("
1<data> <vehicledata><driverdata></driverdata> </vehicledata></data>

") myDoc.AddNodes(docVehicle.SelectNodes("//Record"), "VehicleRecord", " Vehicle Data") myDoc.AddNodes(docDriver.SelectNodes("//Record"), "DriverRecord", "DriverData")

结果如下:


 _myDoc.xml_
 1<data>
 2<vehicledata>
 3<vehiclerecord>
 4<id>1001</id>
 5<make>Ford</make>
 6<model>Escort</model>
 7<year>1984</year>
 8</vehiclerecord>
 9<vehiclerecord>
10<id>1002</id>
11<make>Toyota</make>
12<model>Tercel</model>
13<year>1996</year>
14</vehiclerecord>
15<vehiclerecord>
16<id>1003</id>
17<make>Mazda</make>
18<model>GLC</model>
19<year>1985</year>
20</vehiclerecord>
21</vehicledata>
22<driverdata>
23<driverrecord>
24<id>1</id>
25<firstname>Albert</firstname>
26<lastname>Einstein</lastname>
27</driverrecord>
28<driverrecord>
29<id>2</id>
30<firstname>Clint</firstname>
31<lastname>Eastwood</lastname>
32</driverrecord>
33<driverrecord>
34<id>3</id>
35<firstname>James</firstname>
36<lastname>Bond</lastname>
37</driverrecord>
38</driverdata>
39</data>

下面我介绍如何合并节点。假设我们有两个XmlDocument文件docBook1和docBook2,

这两个文档都包含
  1<book> 节点.  在docBook1 中的这个 <book> 节点 包含
  2    
  3    
  4     <introduction>, <chapter1>, and <chapter2>.  
  5    
  6    
  7    在docBook2中的这个 <book> 节点 包含 <chapter3>, <chapter4>, and <chapter5>.  
  8    
  9    
 10    下面的代码演示如何合并这两个book节点:
 11    
 12    
 13    Dim myDoc As XMLDocumentEx = New XMLDocumentEx()
 14    myDoc.LoadXml("<data> <book></book></data> ")
 15    myDoc.MergeNode(docBook1.SelectSingleNode("//Book"), "Book", "Data ")
 16    myDoc.MergeNode(docBook2.SelectSingleNode("//Book"), "Book", "Data")
 17    
 18    
 19    合并后的效果如下:
 20    
 21    
 22     _myDoc.xml_
 23    
 24    
 25    <data>
 26<book>
 27<introduction>...</introduction>
 28            &lt; Chapter1 &gt;...</book></data></chapter5></chapter4></chapter3></book></chapter2></chapter1>
 29<chapter2>...</chapter2>
 30<chapter3>...</chapter3>
 31<chapter4>...</chapter4>
 32<chapter5>...</chapter5>
 33</introduction></book>
 34
 35    
 36    
 37    下面是所有的源代码:
 38    
 39    
 40    sealed public class XMLDocumentEx: XmlDocument
 41    {
 42        public bool AddNode(XmlNode oSource, String sName)
 43        {
 44            return AddNode(oSource, sName, null);
 45        }
 46        public bool AddNode(XmlNode oSource, String sName, String sParent)
 47        {
 48            try
 49            {
 50                if(sName!=null&amp;&amp;oSource!= null)
 51                {
 52                    // create the new node with given name
 53                    XmlNode oNewNode = CreateElement(sName);
 54                    // copy the contents from the source node
 55                    oNewNode.InnerXml = oSource.InnerXml;
 56                    // if there is no parent node specified, then add
 57                    // the new node as a child node of the root node
 58                    if(sParent!= null) sParent = sParent.Trim();
 59                    if(sParent== null||sParent.Equals(String.Empty)) 
 60                    {
 61                        DocumentElement.AppendChild(oNewNode);
 62                        return true;
 63                    }
 64                    // otherwise add the new node as a child of the parent node
 65                    else
 66                    {
 67                        if (!sParent.Substring(0,2).Equals("//")) sParent = "//"+sParent;
 68                        XmlNode oParent = SelectSingleNode(sParent);
 69                        if (oParent!=null)
 70                        {
 71                            oParent.AppendChild(oNewNode);
 72                            return true ;
 73                        }
 74                    }
 75                }
 76            }
 77            catch (Exception)
 78            {
 79                // error handling code
 80            }
 81            return false;
 82        }
 83        public bool AddNodes(XmlNodeList oSourceList, String sName)
 84        {
 85            return AddNodes(oSourceList, sName, null);
 86        }
 87        public bool AddNodes(XmlNodeList oSourceList, String sName, String sParent)
 88        {
 89            try
 90            {
 91                if(oSourceList!= null)
 92                {
 93                    // call AddNode for each item in the source node list
 94                    // return true only if all nodes are added successfully
 95                    int i = 0;
 96                    while(i&lt;oSourceList.Count)
 97                    {
 98                        if (!AddNode(oSourceList.Item(i),sName,sParent)) return false;
 99                        i++;
100                    }
101                    return true;
102                }
103            }
104            catch (Exception)
105            {
106                // error handling code
107            }
108            return false;
109        }
110        public bool MergeNode(XmlNode oSource, String sName)
111        {
112            return MergeNode(oSource, sName, null );
113        }
114        public bool MergeNode(XmlNode oSource, String sName, String sParent)
115        {
116            try
117            {
118                if(sName!=null&amp;&amp;oSource!= null)
119                {
120                    XmlNode theNode = null ;
121                    // if there is no parent node specified ...
122                    if(sParent!= null) sParent = sParent.Trim();
123                    if(sParent== null||sParent.Equals(String.Empty)) 
124                    {
125                        // if the node with specified name does not exist,
126                        // add it as a child node of the root node
127                        theNode = SelectSingleNode("//"+sName);
128                        if (theNode==null)
129                        {
130                            theNode = CreateElement(sName);
131                            DocumentElement.AppendChild(theNode);
132                        }
133                    }
134                    // if the parent node is specified ...
135                    else
136                    {
137                        // find the parent node
138                        if (!sParent.Substring(0,2).Equals("//")) sParent = "//"+sParent;
139                        XmlNode theParent = SelectSingleNode(sParent);
140                        if (theParent!=null)
141                        {
142                            // if the node with specified name does not exist, create
143                            // it first, then add it as a child node of the parent node
144                            theNode = theParent.SelectSingleNode(sName);
145                            if(theNode==null)
146                            {
147                                theNode = CreateElement(sName);
148                                theParent.AppendChild(theNode);
149                            }
150                        }
151                    }
152                    // merge the content of the source node into
153                    // the node with specified name
154                    if(theNode!= null) 
155                    {
156                        theNode.InnerXml += oSource.InnerXml;
157                        return true;
158                    }
159                }
160            }
161            catch (Exception)
162            {
163            }
164            return false;
165        }
166    }</book>
Published At
Categories with Web编程
Tagged with
comments powered by Disqus