简体   繁体   中英

Reading value of an XML node

i need to get the value of an Node in an XML File.

My XML file looks like this:

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

I want to get the text (iPhone 5s) from the file. I have tried several things I have found on the internet:

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

No method seems to work. When i run the project (ASP.NET Project) i get the following error:

System.NullReferenceException: Object reference not set to an instance to an object

How can i get the values of the nodes?

You can use Linq To Xml.

Assuming you you have other products like IPHONE under 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();

You may also want to have a look at the methods given below.

1) XmlDocument and XmlNode

2) Serialization and Deserialization .

3) Simplified example of Serialization and Deserialization

I suggest to use 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")          
};

Then you can use name, model, price or color of iPhone object. Eg

iPhone.Name

Note - if there is many iPhones in file, you can grab them all:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM