xml文件格式如下:
<?xml version="1.0" encoding="UTF-8" ?>
<Product type="15" total="35">
<type>
<T gid="1" sum="100" />
<T gid="2" sum="200" />
<T gid="3" sum="100" />
</type>
<Mobile>
<G gn="诺基亚" pr="1800" sum="100" />
<G gn="摩托罗拉" pr="1700" sum="200" />
<G gn="三星" pr="1600" sum="300" />
<G gn="飞利浦" pr="1750" sum="90" />
</Mobile>
</Product>
//-----------------------------------
我需要读取Product节点的type(15) total(35)值 以及 Mobile节点下的子节点G里面的属性gn、pr、sum的值.
最好把type节点下的T 属性也读取出来
XmlTextReader xml = new XmlTextReader(xmlfile);
while (xml.Read())
{
这里如何写代码?
textBox1 .AppendText();//将属性值分行输出至textBox1,格式为:商品:诺基亚 - 价钱:1800 - 数量:100
}
class MyXMLTextReader
{
static void Main(string[] args)
{
XmlTextReader xml = new XmlTextReader(@"Product.xml");
xml.WhitespaceHandling = WhitespaceHandling.None;
while (xml.Read())
{
if (xml.NodeType == XmlNodeType.Element)
{
if (xml.Name == "Product")
ReadTypeAndTotal(xml);
else if (xml.Name == "Mobile")
ReadG(xml);
}
}
Console.ReadKey(true);
}
// 读取Product节点的type(15) total(35)值
private static void ReadTypeAndTotal(XmlTextReader xml)
{
Console.Write("Product节点的type: ");
Console.WriteLine(xml.GetAttribute("type"));
Console.Write("Product节点的total: ");
Console.WriteLine(xml.GetAttribute("total"));
}
// Mobile节点下的子节点G里面的属性gn、pr、sum的值
private static void ReadG(XmlTextReader xml)
{
Console.WriteLine();
while (xml.Read())
{
if (xml.NodeType == XmlNodeType.Element)
{
if (xml.Name != "G")
break;
Console.Write("商品:");
Console.Write(xml.GetAttribute("gn"));
Console.Write(" - ");
Console.Write("价钱:");
Console.Write(xml.GetAttribute("pr"));
Console.Write(" - ");
Console.Write("数量:");
Console.WriteLine(xml.GetAttribute("sum"));
}
}
}
}