使用DOM读取节点属性!

 1 using System;
 2 using System.IO;
 3 using System.Xml;
 4 namespace XML_Attribute1 {
 5     class Class1 {
 6         [STAThread]
 7         static void Main(string[] args) {
 8             XmlDocument doc=new XmlDocument();
 9             doc.LoadXml("<book genre='novel' ISBN='1-861001-57-5' misc='sale item'>" +
10                 "<title>The Handmaid's Tale</title>" +
11                 "<price>14.95</price>" +
12                 "</book>");
13             XmlElement myElement=doc.DocumentElement;
14             XmlAttributeCollection attrColl=myElement.Attributes;
15             Console.WriteLine("Display all the attributes in the collection");
16             for (int i=0;i<attrColl.Count;i++) {
17                 Console.Write("{0}=",attrColl[i].Name);
18                 Console.Write("{0}",attrColl[i].Value);
19                 Console.WriteLine();
20             }
21             XmlAttribute attr=attrColl["misc"];
22             string miscValue=attr.InnerText;
23             Console.WriteLine("Display the attribute information.");
24             Console.WriteLine(miscValue);
25         }
26     }
27 }
28

显示集合中的所有属性。

genre = novel
ISBN = 1-861001-57-5
misc = sale item
Display the attribute information.
sale item
 1 检索单个属性节点
 2 若要从一个元素中检索出单个属性节点,应使用 XmlElement.GetAttributeNode 方法。它返回一个类型为 XmlAttribute 的对象。有了 XmlAttribute 对象后,XmlAttribute 成员类中所有可用的方法和属性都可以用于该对象,例如查找 OwnerElement。
 3
34 
35 [C#]
36 using System;
37 using System.IO;
38 using System.Xml;
39  
40  public class Sample
41  {
42       public static void Main()
43       {
44     XmlDocument doc = new XmlDocument();
45      doc.LoadXml("<book genre='novel' ISBN='1-861003-78' misc='sale item'>" +
46                    "<title>The Handmaid's Tale</title>" +
47                    "<price>14.95</price>" +
48                    "</book>"); 
49 
50     // Move to an element.
51      XmlElement root = doc.DocumentElement;
52    
53     // Get an attribute.
54      XmlAttribute attr = root.GetAttributeNode("ISBN");
55   
56     // Display the value of the attribute.
57      String attrValue = attr.InnerXml;
58      Console.WriteLine(attrValue);
59 
60     }
61 }
62 
63 您也可以如前例所示,从属性集合中检索单个属性节点。下面的代码示例显示了如何编写一行代码来按索引编号从 XML 文档树(也叫 DocumentElement 属性)的根节点检索单个属性。
64 
65 XmlAttribute attr = doc.DocumentElement.Attributes[0];
66 

posted @ 2006-09-04 13:53  吴东雷  阅读(647)  评论(0)    收藏  举报