如何用XmlReader得到XmlNode
XmlDocument.ReadNode 方法
根据 XmlReader 中的信息创建一个 XmlNode 对象。读取器必须定位在节点或属性上。
备注
从给定的读取器读取一个 XmlNode 并将读取器定位在下一个节点上。该方法创建与读取器当前定位在其上的 NodeType 匹配的 XmlNode 的类型。(如果读取器处于初始状态,则 ReadNode 将读取器推进到第一个节点,然后对该节点进行操作。)
如果读取器定位在元素的开始处,则 ReadNode 读取所有属性和任何子节点,直到(并包括)当前节点的结束标记。返回的 XmlNode 包含表示所读取所有内容的子树。读取器的定位紧接在结束标记之后。
ReadNode 还可以读取属性,但在这种情况下它不将读取器推进到下一个属性。这允许您编写下面的 C# 代码:
using System;using System.IO;using System.Xml;public class Sample{ public static void Main() { //Create the XmlDocument. XmlDocument doc = new XmlDocument(); doc.LoadXml("<bookstore>" + "<book genre='novel' ISBN='1-861001-57-5'>" + "<title>Pride And Prejudice</title>" + "</book>" + "</bookstore>"); //Create a reader. XmlTextReader reader = new XmlTextReader("cd.xml"); reader.MoveToContent(); //Move to the cd element node. //Create a node representing the cd element node. XmlNode cd = doc.ReadNode(reader); //Insert the new node into the document. doc.DocumentElement.AppendChild(cd); Console.WriteLine("Display the modified XML..."); doc.Save(Console.Out); }}
*************************************************************************************************
因为做 windows CE 开发 ,想做个类似于 configuration 类来读取配置文件,用xmlreader 来读取节点和属性,
但现在只会读取节点,请问怎么读取属性。
以下示例使用 AttributeCount 属性读取某个元素的所有属性。
// Display all attributes.
if (reader.HasAttributes) {
Console.WriteLine("Attributes of <" + reader.Name + ">");
for (int i = 0; i < reader.AttributeCount; i++) {
Console.WriteLine(" {0}", reader[i]);
}
// Move the reader back to the element node.
reader.MoveToElement();
}
以下示例在 While 循环中使用 MoveToNextAttribute 属性读取某个元素的所有属性
if (reader.HasAttributes) {
Console.WriteLine("Attributes of <" + reader.Name + ">");
while (reader.MoveToNextAttribute()) {
Console.WriteLine(" {0}={1}", reader.Name, reader.Value);
}
// Move the reader back to the element node.
reader.MoveToElement();
}
以下示例按名称获取属性的值。
reader.ReadToFollowing("book");
string isbn = reader.GetAttribute("ISBN");
Console.WriteLine("The ISBN value: " + isbn);
using (XmlReader reader = XmlReader.Create(xmlFilePath))
{
while (tr.Read()){
if (tr.NodeType == XmlNodeType.Element){
for (int i = 0; i < tr.AttributeCount; i++){
richTextBox1.AppendText(tr.GetAttribute(i)+"\r\n");
}
}
}
using (XmlReader reader = XmlReader.Create(xmlFilePath))
{
while (reader .Read()){
if (reader.NodeType == XmlNodeType.Element){
for (int i = 0; i < reader.AttributeCount; i++){
str+=reader.GetAttribute(i)+"\r\n");
}
}
}
}
C# code XmlDocument doc = new XmlDocument();
doc.Load(url);
XmlNodeList list = doc.GetElementsByTagName("item");
XmlElement xe = (XmlElement)list[zb];
xe.GetElementsByTagName("pubDate")[0].InnerText;
C# code XmlDocument doc=new XmlDocument();
doc.Load(url);
XmlNodeList list= doc.GetElementsByTagName("item");
XmlElement xe= (XmlElement)list[zb];
xe.GetElementsByTagName("pubDate")[0].InnerText;
大家能不能提供在 WINDOWS CE 中运行的最佳方法啊