Csharp/C Sharp/XML LINQ/XElement

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Accessing the XML Document from an XElement Object via the Document Property

<source lang="csharp"> using System; using System.Linq; using System.Collections; using System.Collections.Generic; using System.Xml; using System.Xml.Linq; public class MainClass {

   public static void Main() {
       XElement firstParticipant;
       XDocument xDocument =  new XDocument(new XDeclaration("1.0", "UTF-8", "yes"),
       new XDocumentType("Books", null, "Books.dtd", null),
       new XProcessingInstruction("Book", "out-of-print"),
       new XElement("Books", firstParticipant =
         new XElement("Book",
          new XAttribute("type", "Author"),
       new XElement("FirstName", "J"),
       new XElement("LastName", "R")),
     new XElement("Book",
       new XAttribute("type", "Author"),
       new XElement("FirstName", "E"),
       new XElement("LastName", "B"))));
       Console.WriteLine(firstParticipant.Document);
   }

}

</source>


Adding a Node to the End of the Specified Node"s Child Nodes with Add

<source lang="csharp"> using System; using System.Linq; using System.Collections; using System.Collections.Generic; using System.Xml; using System.Xml.Linq; public class MainClass {

   public static void Main() {
       XDocument xDocument = new XDocument(
         new XElement("Books",
           new XElement("Book",
             new XAttribute("type", "Author"),
             new XElement("FirstName", "J"),
             new XElement("LastName", "R"))));
       xDocument.Element("Books").Add(
         new XElement("Book",
           new XAttribute("type", "Author"),
           new XElement("FirstName", "E"),
           new XElement("LastName", "B")));
       Console.WriteLine(xDocument);
   }

}

</source>


An Example with a Single Book

<source lang="csharp"> using System; using System.Linq; using System.Collections; using System.Collections.Generic; using System.Xml; using System.Xml.Linq; public class MainClass {

   public static void Main() {
       XDocument xDocument = new XDocument(
         new XElement("Books",
           new XElement("Book",
             new XAttribute("type", "Author"),
             new XElement("FirstName", "J"),
             new XElement("LastName", "R"))));
       Console.WriteLine(xDocument);
   }

}

</source>


Calling the ToString Method on an Element Produces the XML Tree

<source lang="csharp"> using System; using System.Linq; using System.Collections; using System.Collections.Generic; using System.Xml; using System.Xml.Linq; public class MainClass {

   public static void Main() {
       XElement name = new XElement("Name", "Joe");
       Console.WriteLine(name.ToString());
   }

}

</source>


Casting an Element to Its Value"s Data Type Outputs the Value

<source lang="csharp"> using System; using System.Linq; using System.Collections; using System.Collections.Generic; using System.Xml; using System.Xml.Linq; public class MainClass {

   public static void Main() {
       XElement name = new XElement("Name", "Joe");
       Console.WriteLine(name);
       Console.WriteLine((string)name);
   }

}

</source>


Casting a Node to a Different Data Type Than Its Value"s Original Data Type

<source lang="csharp"> using System; using System.Linq; using System.Collections; using System.Collections.Generic; using System.Xml; using System.Xml.Linq; public class MainClass {

   public static void Main() {
       XElement smoker = new XElement("Smoker", "true");
       Console.WriteLine(smoker);
       Console.WriteLine((bool)smoker);
   }

}

</source>


Creates the XML Tree

<source lang="csharp"> using System; using System.Linq; using System.Collections; using System.Collections.Generic; using System.Xml; using System.Xml.Linq; public class MainClass {

   public static void Main() {
       XElement xBooks =
       new XElement("Books",
       new XElement("Book",
       new XAttribute("type", "Author"),
       new XElement("FirstName", "J"),
       new XElement("LastName", "R")),
       new XElement("Book",
       new XAttribute("type", "Author"),
       new XElement("FirstName", "E"),
       new XElement("LastName", "B")));
       Console.WriteLine(xBooks.ToString());
   }

}

</source>


Create XML document from object list

<source lang="csharp"> using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.Linq; using System.Reflection; using System.Xml.Linq; class Employee {

   int _id;
   int _idRole;
   string _lastName;
   string _firstName;
   public int ID {
       get { return _id; }
       set { _id = value; }
   }
   public int IDRole {
       get { return _idRole; }
       set { _idRole = value; }
   }
   public string LastName {
       get { return _lastName; }
       set { _lastName = value; }
   }
   public string FirstName {
       get { return _firstName; }
       set { _firstName = value; }
   }

} class Program {

   static void Main(string[] args) {
       List<Employee> people = new List<Employee> {
              new Employee { ID = 1, IDRole = 1, LastName = "A", FirstName = "B"},
              new Employee { ID = 2, IDRole = 2, LastName = "G", FirstName = "T"}
           };
       XElement xml = new XElement("people",
                               from p in people
                               select new XElement("person",
                                           new XElement("id", p.ID),
                                           new XElement("firstname", p.FirstName),
                                           new XElement("lastname", p.LastName),
                                           new XElement("idrole", p.IDRole)));
       Console.WriteLine(xml);
   }

}

</source>


Creating an Element Using the First Prototype

<source lang="csharp"> using System; using System.Linq; using System.Collections; using System.Collections.Generic; using System.Xml; using System.Xml.Linq; public class MainClass {

   public static void Main() {
       XElement firstName = new XElement("FirstName", "Joe");
       Console.WriteLine((string)firstName);
   }

}

</source>


Different Node Value Types Retrieved via Casting to the Node Value"s Type

<source lang="csharp"> using System; using System.Linq; using System.Collections; using System.Collections.Generic; using System.Xml; using System.Xml.Linq; public class MainClass {

   public static void Main() {
       XElement count = new XElement("Count", 12);
       Console.WriteLine(count);
       Console.WriteLine((int)count);
       XElement smoker = new XElement("Smoker", false);
       Console.WriteLine(smoker);
       Console.WriteLine((bool)smoker);
       XElement pi = new XElement("Pi", 3.1415926535);
       Console.WriteLine(pi);
       Console.WriteLine((double)pi);
   }

}

</source>


Generates an Empty Element

<source lang="csharp"> using System; using System.Linq; using System.Collections; using System.Collections.Generic; using System.Xml; using System.Xml.Linq; public class MainClass {

   public static void Main() {
       IEnumerable<XElement> elements =
         new XElement[] {
   new XElement("Book",
     new XElement("Name", "J"),
     new XElement("Book", "LINQ")),
   new XElement("Book",
     new XElement("Name", "J"))};
       XElement xElement =
         new XElement("Books",
           elements.Select(e =>
            new XElement(e.Name,
              new XElement(e.Element("Name").Name, e.Element("Name").Value),
              new XElement("Books", e.Elements("Book")))));
       Console.WriteLine(xElement);
   }

}

</source>


Handling Multiple Peer Nodes While Maintaining a Flat Structure

<source lang="csharp"> using System; using System.Linq; using System.Collections; using System.Collections.Generic; using System.Xml; using System.Xml.Linq; public class MainClass {

   public static void Main() {
       XDocument xDocument = new XDocument(
         new XElement("Books",
           new XElement("Book",
           new XAttribute("type", "Author"),
           new XElement("FirstName", "A"),
           new XElement("LastName", "B"),
           new XElement("Nickname", "A"),
           new XElement("Nickname", "Null Pointer")),
         new XElement("Book",
           new XAttribute("type", "Author"),
           new XElement("FirstName", "C"),
           new XElement("LastName", "D"))));
       Console.WriteLine(xDocument);
   }

}

</source>


Immediate Execution of the XML Tree Construction

<source lang="csharp"> using System; using System.Linq; using System.Collections; using System.Collections.Generic; using System.Xml; using System.Xml.Linq; public class MainClass {

   public static void Main() {
       string[] names = { "J", "P", "G", "P" };
       XElement xNames = new XElement("Beatles",
              from n in names
              select new XElement("Name", n));
       names[3] = "R";
       Console.WriteLine(xNames);
   }

}

</source>


Is an element empty

<source lang="csharp"> using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.Linq; using System.Reflection; using System.Xml.Linq; class Program {

   static void Main(string[] args) {
       XElement xml = XElement.Load("Employee.xml");
       XElement firstName = xml.Descendants("firstname").First();
       Console.WriteLine("Is FirstName tag empty? {0}", firstName.IsEmpty ? "Yes" : "No");
       XElement idEmployee = xml.Descendants("idperson").First();
       Console.WriteLine("Is idperson tag empty? {0}", idEmployee.IsEmpty ? "Yes" : "No");
   }

}

</source>


Loading an Element with the XElement.Load Method

<source lang="csharp"> using System; using System.Linq; using System.Collections; using System.Collections.Generic; using System.Xml; using System.Xml.Linq; public class MainClass {

   public static void Main() {
       XElement xElement = XElement.Load("book.xml");
       Console.WriteLine(xElement);
   }

}

</source>


Obtaining Elements Without Reaching

<source lang="csharp"> using System; using System.Linq; using System.Collections; using System.Collections.Generic; using System.Xml; using System.Xml.Linq; public class MainClass {

   public static void Main() {
       XDocument xDocument = new XDocument(
         new XElement("Books",
         new XElement("Book",
         new XAttribute("type", "Author"),
         new XElement("FirstName", "A"),
         new XElement("LastName", "B")),
         new XElement("Book",
         new XAttribute("type", "Author"),
         new XElement("FirstName", "C"),
         new XElement("LastName", "D"))));
       IEnumerable<XElement> elements = xDocument.Descendants("Book");
       foreach (XElement element in elements) {
           Console.WriteLine("Element: {0} : value = {1}",element.Name, element.Value);
       }
   }

}

</source>


Obtaining Restricted Elements Without Reaching

<source lang="csharp"> using System; using System.Linq; using System.Collections; using System.Collections.Generic; using System.Xml; using System.Xml.Linq; public class MainClass {

   public static void Main() {
       XDocument xDocument = new XDocument(
         new XElement("Books",
           new XElement("Book",
             new XAttribute("type", "Author"),
             new XElement("FirstName", "A"),
             new XElement("LastName", "B")),
         new XElement("Book",
           new XAttribute("type", "Author"),
           new XElement("FirstName", "C"),
           new XElement("LastName", "D"))));
       IEnumerable<XElement> elements = xDocument.Descendants("Book")
          .Where(e => ((string)e.Element("FirstName")) == "C");
       foreach (XElement element in elements) {
           Console.WriteLine("Element: {0} : value = {1}",element.Name, element.Value);
       }
   }

}

</source>


Obtaining Restricted Elements Without Reaching While Ordering and Using Query Expression Syntax

<source lang="csharp"> using System; using System.Linq; using System.Collections; using System.Collections.Generic; using System.Xml; using System.Xml.Linq; public class MainClass {

   public static void Main() {
       XDocument xDocument = new XDocument(
         new XElement("Books",
           new XElement("Book",
             new XAttribute("type", "Author"),
             new XElement("FirstName", "A"),
             new XElement("LastName", "B")),
          new XElement("Book",
            new XAttribute("type", "Author"),
            new XElement("FirstName", "C"),
            new XElement("LastName", "D"))));
       IEnumerable<XElement> elements =
         from e in xDocument.Descendants("Book")
         where ((string)e.Attribute("type")) != "Illustrator"
         orderby ((string)e.Element("LastName"))
         select e;
       foreach (XElement element in elements) {
           Console.WriteLine("Element: {0} : value = {1}",element.Name, element.Value);
       }
   }

}

</source>


Parsing an XML String into an Element

<source lang="csharp"> using System; using System.Linq; using System.Collections; using System.Collections.Generic; using System.Xml; using System.Xml.Linq; public class MainClass {

   public static void Main() {
       string xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><Books>" +
     "<Book type=\"Author\" experience=\"first-time\" language=" +
     "\"English\"><FirstName>J</FirstName><LastName>R</LastName>" +
     "</Book></Books>";
       XElement xElement = XElement.Parse(xml); 
       Console.WriteLine(xElement);
   }

}

</source>


Prevents an Empty Element

<source lang="csharp"> using System; using System.Linq; using System.Collections; using System.Collections.Generic; using System.Xml; using System.Xml.Linq; public class MainClass {

   public static void Main() {
       IEnumerable<XElement> elements =
         new XElement[] {
   new XElement("Book",
     new XElement("Name", "J"),
     new XElement("Book", "LINQ")),
   new XElement("Book",
     new XElement("Name", "J"))};
       XElement xElement =
         new XElement("Books",
           elements.Select(e =>
             new XElement(e.Name,
             new XElement(e.Element("Name").Name, e.Element("Name").Value),
          e.Elements("Book").Any() ?
            new XElement("Books", e.Elements("Book")) : null)));
       Console.WriteLine(xElement);
   }

}

</source>


Saving an Element with the XElement.Save Method

<source lang="csharp"> using System; using System.Linq; using System.Collections; using System.Collections.Generic; using System.Xml; using System.Xml.Linq; public class MainClass {

   public static void Main() {
       XElement bookParticipants =
        new XElement("Books",
        new XElement("Book",
        new XAttribute("type", "Author"),
        new XAttribute("experience", "first-time"),
        new XAttribute("language", "English"),
        new XElement("FirstName", "J"),
        new XElement("LastName", "R")));
       bookParticipants.Save("book.xml");
   }

}

</source>


Suppressing Node Construction with null

<source lang="csharp"> using System; using System.Linq; using System.Collections; using System.Collections.Generic; using System.Xml; using System.Xml.Linq; public class MainClass {

   public static void Main() {
       IEnumerable<XElement> elements =new XElement[] {new XElement("Element", "A"),new XElement("Element", "B")};
       XElement xElement = new XElement("RootElement", elements.Select(e => (string)e != "A" ? new XElement(e.Name, (string)e) : null));
       Console.WriteLine(xElement);
   }

}

</source>


The Elements method returns just the child nodes of type XElement

<source lang="csharp"> using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; public class MainClass {

   public static void Main() {
       var bench = new XElement("bench",
                     new XElement("A",
                       new XElement("B", "H"),
                       new XElement("B", "R")
                     ),
                     new XElement("A",
                       new XElement("B", "S"),
                       new XElement("C", "N")
                     ),
                     new XComment("comment")
                   );
       foreach (XElement e in bench.Elements())
           Console.WriteLine(e.Name + "=" + e.Value);
   }

}

</source>


Use XElement.Parse to parse an element document

<source lang="csharp"> using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.Linq; using System.Reflection; using System.Xml.Linq; class Program {

   static void Main(string[] args) {
       string doc = @"<people>
                         
                         <person>
                           <id>1</id>
                           <firstname>C</firstname>
                           <lastname>L</lastname>
                           <idrole>1</idrole>
                         </person>
                          </people>";
       XElement xml = XElement.Parse(doc);
       Console.WriteLine(xml);
   }

}

</source>


XElement.Load("Employee.xml")

<source lang="csharp"> using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.Linq; using System.Reflection; using System.Xml.Linq; class Program {

   static void Main(string[] args) {
       XElement xml = XElement.Load("Employee.xml");
       xml.Descendants("idperson").First().Remove();
       xml.Elements("role").Remove();
       Console.WriteLine(xml);
   }

}

</source>