c#中xmlreader是怎么读数据的
1个回答
展开全部
看下面的例子
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Xml;
usingSystem.IO;
namespacetryXmlreader
{
class Program
{
static voidMain(string[] args)
{
//CreateByFile();
//CreateByFileStream();
//ReadElementContentAs();
ReadAttribute();
//Console.ReadLine();
}
public staticvoid CreateByFile()
{
//创建XML读取器,读取XML文件
XmlReaderreader = XmlReader.Create(@"e:\1.xml");
Console.WriteLine("All Text in books.xml:\n");
while(reader.Read())
{
if(reader.NodeType == XmlNodeType.Text)
{
Console.WriteLine(reader.Value);
}
}
reader.Close();
}
public staticvoid CreateByFileStream()
{
FileStreamfs = new FileStream(@"e:\1.xml", FileMode.Open);
//创建XML读取器,读取XML文件流
XmlReaderreader = XmlReader.Create(fs);
Console.WriteLine("\nAll title in books.xml:\n");
//循环查找节点,直到最后一个节点
while(!reader.EOF)
{
if(reader.MoveToContent() == XmlNodeType.Element&& reader.Name == "title")
{
//打印节点类型为Element,名称为title的节点值
DisplayElementString(reader);
}
else
{
reader.Read();
}
}
reader.Close();
fs.Close();
}
public staticvoid DisplayElementString(XmlReader reader)
{ try
{
Console.WriteLine(reader.ReadElementString());
}
//捕捉不包含文本内容的元素抛出的异常
catch(XmlException e)
{
}
}
publicstatic voidReadElementContentAs()
{
XmlReaderreader = XmlReader.Create(@"e:\1.xml");
Console.WriteLine("\nAfter update price * 0.8:\n");
while(reader.Read())
{
if(reader.NodeType == XmlNodeType.Element)
{
if(reader.Name == "price")
{
//将price元素值读取为decimal类型
decimal price = reader.ReadElementContentAsDecimal();
price = price * 0.8m;
Console.WriteLine("New Price ={0}", price);
}
elseif (reader.Name == "title")
{
//将title元素值读取为string类型
Console.WriteLine(reader.ReadElementContentAsString());
}
}
}
reader.Close();
}
public staticvoid ReadAttribute()
{
XmlReaderreader = XmlReader.Create(@"e:\1.xml");
Console.WriteLine("\nAttribute:\n");
while(reader.Read())
{
if(reader.NodeType == XmlNodeType.Element)
{
for(int i = 0; i < reader.AttributeCount; i++)//迭代其所有属性
{
Console.WriteLine(reader.GetAttribute(i));
}
}
}
reader.Close();
}
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询