Reading value of an XML node

前端 未结 3 918
执笔经年
执笔经年 2021-01-28 22:54

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

My XML file looks like this:





        
相关标签:
3条回答
  • 2021-01-28 23:20

    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();
    
    0 讨论(0)
  • 2021-01-28 23:25

    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. E.g.

    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") 
                  };
    
    0 讨论(0)
  • 2021-01-28 23:28

    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

    0 讨论(0)
提交回复
热议问题