C Linq reads an instance of the XML file

  • 2020-05-12 03:03:05
  • OfStack

1. Example XML file: Demo.xml


<?xml version="1.0" encoding="utf-8" ?>
<note>
  <conf>
    <to>infozero</to>
    <from>lerroy</from>
    <heading> The test information </heading>
    <body> The first 1 Bar test information </body>
    <title name=" My first 1 message ">from myself</title>
  </conf>
  <conf>
    <to>infozero@163.com</to>
    <from>text</from>
    <heading>  Remind me all the time  </heading>
    <body> This is a 1 Bar test information! </body>
    <title name=" My first 2 message ">from others</title>
  </conf>
</note>

2. Refer to the following namespace in your program


using System;
using System.Linq;
using System.Xml.Linq;

3. Read the code as follows:


class Program
    {
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load("demo.xml");
            var text = from t in doc.Descendants("conf")                    // Position to node  
                       .Where(w => w.Element("to").Value.Contains('@'))   // Use this statement to filter  
                       select new
                       {
                           to = t.Element("to").Value,
                           froms = t.Element("from").Value,
                           head = t.Element("heading").Value,
                           body = t.Element("body").Value,
                           title = t.Element("title").Attribute("name").Value   // Notice the use of  attribute 
                       };
            foreach (var a in text)
            {
                Console.WriteLine(a.to);
                Console.WriteLine(a.froms);
                Console.WriteLine(a.head);
                Console.WriteLine(a.body);
                Console.WriteLine(a.title);
            }
            Console.ReadKey();
        }
    }


Related articles: