读取XML节点的值

我需要在XML文件中获取Node的值。

我的XML文件如下所示:

   iPhone 5s 5s 899 Gold  

我想从文件中获取文本(iPhone 5s)。 我尝试过在互联网上找到的几件事:

 protected void Page_Load(object sender, EventArgs e) { String[][] products = new String[3][]; int i = 0; int j = 0; System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader("../XML-Test/Webshop-products.xml"); while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { if (reader.LocalName.Equals("NAME")) { //Name of product products[i][j] = reader.ReadInnerXml(); j++; } if (reader.LocalName.Equals("MODEL")) { //Model products[i][j] = reader.ReadString(); j++; } if (reader.LocalName.Equals("PRICE")) { //Price products[i][j] = reader.Value; j++; } if (reader.LocalName.Equals("COLOR")) { //Color products[i][j] = reader.Value; j++; i++; } } } for (int k = 0; k < products.Length; k++) { for (int l = 0; l < products[k].Length; l++) { Console.Write(products[k][l]); } } } 

没有方法似乎有效。 当我运行该项目(ASP.NET项目)时,我收到以下错误:

System.NullReferenceException:未将对象引用设置为对象的实例

我怎样才能获得节点的值?

您可以使用Linq To Xml。

假设您在PRODUCTS下还有其他产品,如IPHONE

 var products = XDocument.Load(filename).Root .Elements() .Select(x => new { Product = x.Name.LocalName, Name = (string)x.Element("NAME"), Model = (string)x.Element("MODEL"), Price = (decimal)x.Element("PRICE"), Color = (string)x.Element("COLOR") }) .ToList(); 

我建议使用Linq to Xml:

 var xdoc = XDocument.Load("../XML-Test/Webshop-products.xml"); var p = xdoc.Root.Element("IPHONE"); // get first IPHONE from file if (iPhoneElement == null) return; // handle case when there is no IPHONE in xml file var iPhone = new { Name = (string)p.Element("NAME"), Model = (string)p.Element("MODEL"), Price = (decimal)p.Element("PRICE"), Color = (string)p.Element("COLOR") }; 

然后你可以使用iPhone对象的名称,型号,价格或颜色。 例如

 iPhone.Name 

注意 – 如果文件中有许多iPhone,您可以全部抓取它们:

 var iPhones = from p in xdoc.Root.Elements("IPHONE") select new { Name = (string)p.Element("NAME"), Model = (string)p.Element("MODEL"), Price = (decimal)p.Element("PRICE"), Color = (string)p.Element("COLOR") }; 

您可能还想查看下面给出的方法。

1) XmlDocument和XmlNode

2) 序列化和反序列化 。

3) 序列化和反序列化的简化示例