通过使用DOM: Document Object Model操控XML文档
什么时候使用DOM
Before you go ahead and use DOM for accessing your XML documents, you should understand
the areas to which DOM is best suited and areas where its use should be avoided.
The decision of whether to use DOM is governed by the following core factors:
Read/write access: DOM allows you to read and write the XML document. But do you really
need to change the underlying document?
Memory footprint: DOM loads the entire document in memory. Naturally the memory
footprint of DOM is larger. Are your documents large, say over 100MB?
Type of access: DOM allows you to access any node randomly. This is possible because the
entire document tree is available in memory. Do you need such access? Or is sequential
access sufficient?
Answers to the preceding questions will help you to decide whether to use DOM. To
summarize, DOM is best suited in the following scenarios:
? You want to modify the XML documents, that is, read-only access is not sufficient.
? You want to access various nodes randomly, that is, sequential access is not sufficient.
? You want to process documents that are small in size.
? The memory footprint is not a constraint.
XmlDocument类有三种方式载入XML文档:
- 指定XML文件的路径或者Url地址;
- 通过包括XML文件的文件流等流对象;
- 包括XML文件的内存字符串;
示例代码如下:
1: private void button1_Click(object sender, EventArgs e)
2: {
3: try
4: {
5: XmlDocument doc = new XmlDocument();
6: if (radioButton1.Checked)
7: {
8: //用Url方式载入XML文件
9: doc.Load(textBox1.Text);
10: }
11: if (radioButton2.Checked)
12: {
13: //用文件流的方式载入XML文件
14: FileStream stream = new FileStream(textBox1.Text, FileMode.Open);
15: doc.Load(stream);
16: stream.Close();
17: }
18: if (radioButton3.Checked)
19: {
20: //用内存中字符串的形式载入XML文件
21: doc.LoadXml(textBox1.Text);
22: }
23: MessageBox.Show("文件成功写入!");
24: }
25: catch (Exception ex)
26: {
27: MessageBox.Show(ex.Message);
28:
29: }
30: }
导航XML文件中的内容
使用TreeView控件来加载如下的XML文档
示例XML文件:
<?xml version="1.0" encoding="utf-8"?>
<!— This is list of employees —>
<employees>
<employee employeeid="1">
<firstname>Nancy</firstname>
<lastname>Davolio</lastname>
<homephone>(206) 555-9857</homephone>
<notes><![CDATA[includes a BA in psychology from Colorado State University in
1970. She also completed "The Art of the Cold Call." Nancy is a member of
Toastmasters International.]]></notes>
original link:
<a href='http://Apiaceae.github.io/blog/2009/04/30/XML%E7%BC%96%E7%A8%8B%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0%28%E4%B8%80%29/'>http://Apiaceae.github.io/blog/2009/04/30/XML%E7%BC%96%E7%A8%8B%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0%28%E4%B8%80%29/</a><br/>
written by <a href='http://Apiaceae.github.io'>Hooker</a>
posted at <a href='http://Apiaceae.github.io'>http://Apiaceae.github.io</a>
</p>