读取XML节点的值

时间:2014-03-15 19:03:00

标签: c# xml

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

我的XML文件如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<PRODUCTS>
<IPHONE>
    <NAME>iPhone 5s</NAME>
    <MODEL>5s</MODEL>
    <PRICE>899</PRICE>
    <COLOR>Gold</COLOR>
</IPHONE>

我想从文件中获取文本(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:未将对象引用设置为对象的实例

如何获取节点的值?

3 个答案:

答案 0 :(得分:1)

您可以使用Linq To Xml。

假设您在IPHONE

下有其他产品,例如PRODUCTS
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();

答案 1 :(得分:0)

答案 2 :(得分:0)

我建议将Linq用于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对象的名称,型号,价格或颜色。 E.g。

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