Csharp/C Sharp by API/System.Xml.Linq/XElement

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

new XElement

   
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 XComment("This is a new 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<XAttribute> attributes = xDocument.Element("Books").Elements("Book").Attributes();
        foreach (XAttribute attribute in attributes) {
            Console.WriteLine("Source attribute: {0} : value = {1}", attribute.Name, attribute.Value);
        }
        attributes.Remove();
        Console.WriteLine(xDocument);
    }
}


XElement.AddFirst

  
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.AddFirst(new XElement("person",
                        new XElement("id", 5),
                        new XElement("firstname", "Tom"),
                        new XElement("lastname", "Cruise"),
                        new XElement("idrole", 1)));
        Console.WriteLine(xml);
    }
}


XElement.Ancestors()

   
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");
        var record = xml.Descendants("firstname").First();
        foreach (var tag in record.Ancestors())
            Console.WriteLine(tag.Name);
    }
}


XElement.AncestorsAndSelf()

  

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 XComment("a new author."),
         new XProcessingInstruction("AuthorHandler", "new"),
         new XAttribute("type", "Author"),
         new XElement("FirstName",
       new XText("A"),
       new XElement("NickName", "J")),
      new XElement("LastName", "R")),
      new XElement("Book",
      new XAttribute("type", "Author"),
      new XElement("FirstName", "E"),
      new XElement("LastName", "B"))));
        foreach (XElement element in firstParticipant.
        Element("FirstName").Element("NickName").AncestorsAndSelf()) {
            Console.WriteLine(element.Name);
        }
    }
}


XElement.AncestorsAndSelf(String tagName)

  

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")),
           new XElement("Book",
            new XAttribute("type", "Author"),
           new XElement("FirstName", "E"),
           new XElement("LastName", "B"))));
        IEnumerable<XElement> elements =
         xDocument.Element("Books").Descendants("FirstName");
        foreach (XElement element in elements) {
            Console.WriteLine("Source element: {0} : value = {1}",element.Name, element.Value);
        }
        foreach (XElement element in elements.AncestorsAndSelf("Book")) {
            Console.WriteLine("Ancestor element: {0}", element.Name);
        }
    }
}


XElement.Attribute

   

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 XElement("Books", firstParticipant =
            new XElement("Book",
              new XAttribute("type", "Author"),
              new XElement("FirstName", "J"),
              new XElement("LastName", "R"))));
        Console.WriteLine(firstParticipant.Attribute("type").Value);
    }
}


XElement.Changed

   

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 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("{0}{1}", xDocument, System.Environment.NewLine);
        firstParticipant.Changing += new EventHandler<XObjectChangeEventArgs>(
          (object sender, XObjectChangeEventArgs cea) =>
            Console.WriteLine("Type of object changing: {0}, Type of change: {1}",
              sender.GetType().Name, cea.ObjectChange));
        firstParticipant.Changed += (object sender, XObjectChangeEventArgs cea) =>
          Console.WriteLine("Type of object changed: {0}, Type of change: {1}",
            sender.GetType().Name, cea.ObjectChange);
        xDocument.Changed += (object sender, XObjectChangeEventArgs cea) =>
          Console.WriteLine("Doc: Type of object changed: {0}, Type of change: {1}{2}",
            sender.GetType().Name, cea.ObjectChange, System.Environment.NewLine);

        firstParticipant.Element("FirstName").Value = "Seph";
        Console.WriteLine("{0}{1}", xDocument, System.Environment.NewLine);
    }
}


XElement.Changing

   
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 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(xDocument);
        firstParticipant.Changing += new EventHandler<XObjectChangeEventArgs>(MyChangingEventHandler);
        firstParticipant.Changed += new EventHandler<XObjectChangeEventArgs>(MyChangedEventHandler);
        xDocument.Changed += new EventHandler<XObjectChangeEventArgs>(DocumentChangedHandler);
    }
    public static void MyChangingEventHandler(object sender, XObjectChangeEventArgs cea)
    {
      Console.WriteLine("Type of object changing: {0}, Type of change: {1}",
        sender.GetType().Name, cea.ObjectChange);
    }

    public static void MyChangedEventHandler(object sender, XObjectChangeEventArgs cea)
    {
      Console.WriteLine("Type of object changed: {0}, Type of change: {1}",
        sender.GetType().Name, cea.ObjectChange);
    }

    public static void DocumentChangedHandler(object sender, XObjectChangeEventArgs cea)
    {
      Console.WriteLine("Doc: Type of object changed: {0}, Type of change: {1}{2}",
        sender.GetType().Name, cea.ObjectChange, System.Environment.NewLine);
    }    
}


XElement.Descendants

   

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");
        var query = from p in xml.Descendants("person")
                    join s in xml.Descendants("id")
                    on (int)p.Element("id") equals (int)s.Attribute("id")
                    select new {
                        FirstName = p.Element("firstname").Value,
                        LastName = p.Element("lastname").Value,
                        Amount = s.Attribute("salaryyear").Value
                    };
        foreach (var record in query) {
            Console.WriteLine("Employee: {0} {1}, Salary {2}", record.FirstName,
                                                            record.LastName,
                                                            record.Amount);
        }
    }
}


XElement.Descendants("firstname").First()

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


XElement.Elements

   
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.Element("Books").Elements("Book");
        foreach (XElement element in elements) {
            Console.WriteLine("Source element: {0} : value = {1}", element.Name, element.Value);
        }
        foreach (XAttribute attribute in elements.Attributes()) {
            Console.WriteLine("Attribute: {0} : value = {1}",
             attribute.Name, attribute.Value);
        }
    }
}


XElement.First

  
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(firstName.Parent);
    }
}


XElement.FirstAttribute

   
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 XElement("Books", firstParticipant =
            new XElement("Book",
              new XAttribute("type", "Author"),
              new XAttribute("experience", "first-time"),
              new XAttribute("language", "English"),
              new XElement("FirstName", "J"),
              new XElement("LastName", "R"))));
        Console.WriteLine(firstParticipant.FirstAttribute.NextAttribute);
    }
}


XElement.GetSchemaInfo()

  
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Schema;
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("MiddleName", "Carson"),
              new XElement("LastName", "B")),
            new XElement("Book",
              new XAttribute("type", "Author"),
              new XElement("FirstName", "C"),
              new XElement("LastName", "D"))));
        Console.WriteLine(xDocument);
        XmlSchemaSet schemaSet = new XmlSchemaSet();
        schemaSet.Add(null, "bookparticipants.xsd");
        xDocument.Validate(schemaSet, (o, vea) => {
               Console.WriteLine(o.GetType().Name);
               Console.WriteLine(vea.Message);
           },true);
        foreach (XElement element in xDocument.Descendants()) {
            Console.WriteLine("Element {0} is {1}", element.Name,
              element.GetSchemaInfo().Validity);
            XmlSchemaElement se = element.GetSchemaInfo().SchemaElement;
            if (se != null) {
                Console.WriteLine(
                  "Schema element {0} must have MinOccurs = {1} and MaxOccurs = {2}{3}",
                  se.Name, se.MinOccurs, se.MaxOccurs, System.Environment.NewLine);
            } else {
                Console.WriteLine();
            }
        }
    }
}


XElement.HasAttributes

  
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("FirstName tag has attributes: {0}", firstName.HasAttributes);
        Console.WriteLine("FirstName tag has child elements: {0}", firstName.HasElements);
        Console.WriteLine("FirstName tag"s parent has attributes: {0}", firstName.Parent.HasAttributes);
        Console.WriteLine("FirstName tag"s parent has child elements: {0}", firstName.Parent.HasElements);
    }
}


XElement.HasElements

  
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("FirstName tag has attributes: {0}", firstName.HasAttributes);
        Console.WriteLine("FirstName tag has child elements: {0}", firstName.HasElements);
        Console.WriteLine("FirstName tag"s parent has attributes: {0}", firstName.Parent.HasAttributes);
        Console.WriteLine("FirstName tag"s parent has child elements: {0}", firstName.Parent.HasElements);
    }
}


XElement.Load(String fileName)

   

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("Hello_XLINQ.xml");
        XNamespace w = "http://schemas.microsoft.ru/office/word/2003/wordml";
        XElement defaultFonts = xml.Descendants(w + "defaultFonts").First();
        Console.WriteLine("Default Fonts: {0}", (string)defaultFonts.Attribute(w + "ascii"));
    }
}


XElement.Nodes()

   

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");
        IEnumerable<XComment> record = xml.Nodes().OfType<XComment>();
        foreach (XComment comment in record)
            Console.WriteLine(comment);
    }
}


XElement.Parent

  
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(firstName.Parent);
    }
}


XElement.Parse(String xml value)

   

using System;
using System.Linq;
using System.Xml.Linq;
public class MainClass {
    public static void Main() {
        XElement books = XElement.Parse(
          @"<books>
        <book>
          <title>P</title>
          <author>J</author>
        </book>
        <book>
          <title>W</title>
          <author>B</author>
        </book>
        <book>
          <title>C</title>
          <author>A</author>
        </book>
    </books>");
        var titles =
         from book in books.Elements("book")
         where (string)book.Element("author") == "J"
         select book.Element("title");
        foreach (var title in titles)
            Console.WriteLine(title.Value);
    }
}


XElement.Remove

  
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 XElement("Books", firstParticipant =
            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"))));
        Console.WriteLine(xDocument);
        firstParticipant.Remove();
        Console.WriteLine(xDocument);
    }
}


XElement.RemoveAll

  
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")),
            new XElement("Book",
              new XAttribute("type", "Author"),
              new XElement("FirstName", "E"),
              new XElement("LastName", "B"))));
        Console.WriteLine(xDocument);
        xDocument.Element("Books").RemoveAll();
        Console.WriteLine(xDocument);
    }
}


XElement.Save(String fileName)

   

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 html = new XElement("HTML",
                                new XElement("BODY",
                                    new XElement("TABLE",
                                        new XElement("TH", "ID"),
                                        new XElement("TH", "Full Name"),
                                        new XElement("TH", "Role"),
                                            from p in xml.Descendants("person")
                                            join r in xml.Descendants("role") on (int)p.Element("idrole") equals (int)r.Element("id")
                                            select new XElement("TR",
                                                            new XElement("TD", p.Element("id").Value),
                                                            new XElement("TD", p.Element("firstname").Value + " " + p.Element("lastname").Value),
                                                            new XElement("TD", r.Element("roledescription").Value)))));
        html.Save(@"C:\People.html");
    }
}


XElement.SetAttributeValue

   
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 XElement("Books", firstParticipant =
            new XElement("Book",
              new XAttribute("type", "Author"),
              new XAttribute("experience", "first-time"),
              new XElement("FirstName", "J"),
              new XElement("LastName", "R"))));
        Console.WriteLine(xDocument);
        firstParticipant.SetAttributeValue("type", "beginner");
        firstParticipant.SetAttributeValue("language", "English");
        firstParticipant.SetAttributeValue("experience", null);
        Console.WriteLine(xDocument);
    }
}


XElement.SetElementValue

  
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 XElement("Books", firstParticipant =
            new XElement("Book",
              new XAttribute("type", "Author"),
              new XElement("FirstName", "J"),
              new XElement("LastName", "R"))));
        Console.WriteLine(xDocument);
        firstParticipant.SetElementValue("FirstName", "Joseph");
        firstParticipant.SetElementValue("MiddleInitial", "C");
        firstParticipant.SetElementValue("LastName", null);
        Console.WriteLine(xDocument);
    }
}