Reading value of an XML node

前端 未结 3 945
执笔经年
执笔经年 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: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") 
                  };
    

提交回复
热议问题