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"));
}
}
}
}