SoFunction
Updated on 2025-03-07

Linq To XML explanation in C#

1. Overview

Overview - LINQ to XML | Official Microsoft Documentation

LINQ to XMLLINQ to XML is a LINQ-enabled memory XML programming interface that allows processing XML in the .NET Framework programming language.

References that need to be added when using LINQ to XML.

  • XElementClass represents an XML element, which is a derived class of the XContainer class, which is derived from the XNode class. An element is a node.
    XElement is one of the most important and basic classes of LINQ to XML, and it contains all the necessary functions to create and manipulate XML elements. Through it, you can create elements, add and modify elements' attributes, manipulate elements' contents, etc.
  • XAttributeClass is used to process attributes, which are name/value pairs associated with elements.
  • XDocumentClasses provide methods for processing valid XML documents, including declarations, comments, and processing instructions. The XDocument class is derived from the XContainer class and can have child nodes. XML standard limit XDocument object only contains a single XElement child node, which serves as the root node or element.

Inheritance relationship:

XNode(Abstract) Class derived classes include: XText, XComment, XDocumentType, XProcessingInstruction, XContainer

XContainer(Abstract) Class derived classes include: XElement, XDocument.

2. Load XML file

1. Enter XML data from the file

//1. Get XML data from the URI, support local path and URL, and support corresponding enumeration settingsXElement xe1 = (@"D:\",);

//2. Load from XmlReaderXmlReader xr = (@"D:\");
XElement xe2 = (xr);

//3. Get data from TextReaderTextReader reader = (@"D:\");
XElement xe3 = (reader);

//4. Read from StreamXElement xe4 = (new FileStream(@"D:\", , ));

2. Enter XML data from the string

string xmlString = "Liu Bei 28";
XElement xe = (xmlString, );

3. Generate XML elements or XML documents

1. Create XML elements

XElement xml =
        new XElement("Persons",
            new XElement("Person",
                new XElement("Name", "Liu Bei"),
                new XElement("Age", "28")
                ),
            new XElement("Person",
                new XElement("Name", "Guan Yu"),
                new XElement("Age", "27")
                )
            );
(@"D:\");

2. Create XML document

//Create processing instructionsXProcessingInstruction instruction = new XProcessingInstruction("xml-stylesheet","href=\"\" type = \"text/css\"");
//Create a declaration objectXDeclaration xDeclaration = new XDeclaration("1.0","GB2312","yes");
//Create a document typeXDocumentType documentType = new XDocumentType("Person", null, "", null);
//Create XmlCData dataXCData data = new XCData("The Magical Liu Bei");
//Create XDocument documentXDocument xDoc = new XDocument();
XElement xml =
    new XElement("Persons",
        new XElement("Person",
            new XAttribute("Description", "This person's posture of dragon and phoenix is ​​the appearance of the sky and the sun;"),
            new XElement("Name", data),
            new XElement("Age", "28")
            ),
        new XElement("Person",
            new XElement("Name", "Guan Yu"),
            new XElement("Age", "27")
            )
        );
(documentType);
(instruction);
 = xDeclaration;
(xml);

(@"D:\");

3. Linq query generates XML

We instantiate a collection of books

Book[] books = new Book[] {
  new Book("Ajax in Action", "Manning", 2005),
  new Book("Windows Forms in Action", "Manning", 2006),
  new Book("RSS and Atom in Action", "Manning", 2006)
};

If we now want to create the collection of Year== 2006 into the following XML format

<books>
 <book title="Windows Forms in Action">
 <publisher>Manning</publisher>
 </book>
 <book title="RSS and Atom in Action">
 <publisher>Manning</publisher>
 </book>
</books>

Using linq method

XElement xml = new XElement("books",
  from book in books
  where  == 2006
  select new XElement("book",
     new XAttribute("title", ),
     new XElement("publisher", )
  )
);
// Show this XML(xml);

Traditional way

XmlDocument doc = new XmlDocument();
XmlElement root = ("books");
foreach (Book book in books)
{
if ( == 2006)
  {
    XmlElement element = ("book");
    ("title", );
    XmlElement publisher = ("publisher");
     = ;
    (publisher);
    (element);
  }
}
(root);
// Show this XML();

4. Transfer the attributes from elements

XML file:

<?xml version="1.0" encoding="utf-8" ?>
<Root Data1="123" Data2="456">
  <Child1>Content</Child1>
</Root>

You can write some procedural code to create elements from attributes and then delete attributes

linq method:

XElement root = ("");
XElement newTree = new XElement("Root",
    ("Child1"),
    from att in ()
    select new XElement(, (string)att)
);
(@"D:\");

Traditional way:

XElement root = ("");
foreach (XAttribute att in ()) {
    (new XElement(, (string)att));
}
().Remove();

5. Convert XmlDocument to XDocument

XmlDocument doc = new XmlDocument();
(xmlStr);   // Convert xml string into xml document object
XDocument xdoc = (); // Convert xmldocument to xdoccument extension methodvar eventId = ("EventID"); //The eventid node under the root nodeif (eventId != null)
{
    (); //15
}

Extended Method

public static class XmlDocumentExtensions
{
    public static XDocument ToXDocument(this XmlDocument document)
    {
        return ();
    }

    public static XDocument ToXDocument(this XmlDocument document, LoadOptions options)
    {
        using (XmlNodeReader reader = new XmlNodeReader(document))
        {
            return (reader, options);
        }
    }
}

4. The output of XML data

XElement has a Save, which has multiple overloads and supports inputting XML data to various places (file address, stream, TextWriter, XmlWriter).

XElement xml =
    new XElement("Persons",
        new XElement("Person",
            new XElement("Name", "Liu Bei"),
            new XElement("Age", "28")
            )
        );
//1, output to file(@"D:\");
//2. Output to TextWriterTextWriter tw = new StringWriter();
//The second parameter SaveOptions enumeration supports formatting, indentation, retaining irrelevant blanks, and removing duplicate namespaces(tw, );
(tw);
//3, output to Streamusing (MemoryStream mem = new MemoryStream())
{
    (mem);
    (Encoding.(()));
}
//4. Output to XmlWriterXmlWriter xw = (@"D:\");
(xw);

();

5. Query

  • Element(): Get the first child element of the current XML element with the specified name
  • Elements(): Get all child elements of the current XML element, or all child elements with the specified name, and returns a collection of elements with available LINQ of type IEnumerable for querying
  • Attribute(): Get the attribute with the specified name of the current XML element
  • Attributes(): Gets all attributes of the current XML element or attributes with the specified name, and returns a LINQ collection of type IEnumerable

1. Query the root element

IEnumerable elements = from e in ("Products")
                                 select e;
foreach (XElement e in elements)
{
    ("{0}-{1}", , );
}

2. Query node

var query = from p in ("Products").Elements("Product")
            where (int)("ProductID") == 1
            orderby ("ID").Value 
            select p;

().ForEach(item =>
{
    ("{0}-{1}-{2}", ("ProductID").Value, ("ProductName").Value, ("UnitPrice").Value);
});

3. Query the descendants’ nodes

The Descendants axis method is similar to the Elements type, but Elements only finds direct child nodes under the current element, while Descendants will traverse child elements at any level under the current element.

var query = from b in ("Book")
            select b;
foreach (var item in query)
{
    (("ProductName").Value);
}

4. Query attributes

            var query = from p in ().OfType()
            where (int)("ID").Value == 1
            select new
            {
                ID = ("ID").Value,
                ProductID = ("ProductID").Value,
                ProductName = ("ProductName").Value
            };

5. Query it and fill it into List:

XElement root = (@"");
var query =
            from ele in ("book")
            select new { author = ("author").Value, 
                        price = ("price").Value
                       };

String xml = null;
foreach (var item in query)
{
    xml = xml + () + "\n -------  \n";
}

6. Operation node

1. Add nodes

  • Add(): Add content at the end of the child content of XContainer.
  • AddFirst(): Add content at the beginning of the child content of XContainer.
  • AddAfterSelf(): Add content after XNode.
  • AddBeforeSelf() : Add content before XNode.
XElement product = new XElement
(
    "Product",
    new XAttribute("ID", 2),
    new XElement("ProductName", "LINQ to Object"),
    new XElement("UnitPrice", 20m),
    new XElement("Remark", "")
);

(product);

2. Modify and replace nodes

  • SetAttributeValue(): Sets the value of the attribute. If the property does not exist, the property is created. If the value is set to null, remove the property.
  • SetElementValue(): Sets the value of the child element. If the element does not exist, the element is created. If the value is set to null, the element is removed.
  • Value: Replace the content of the element (child node) with the specified text.
  • SetValue(): Sets the value of the element.
  • ReplaceAll (): Replace all contents of the element (child nodes and properties).
  • ReplaceAttributes(): Replace the attribute of the element.
  • ReplaceWith(): Replace node with new content.
  • ReplaceNodes(): Replace child nodes with new content.
IEnumerable products = from e in ("Product")
                                    where ("ID").Value == "1"
                                    select e;
if (() > 0)
{
    XElement product = ();
    ("ID", 3);
    
    (
        new XElement("ProductName", "LINQ to XML Version 2"),
        new XElement("UnitPrice", 30)
    );
}

3. Delete nodes

  • RemoveAll(): Removes all contents of the element (child nodes and attributes).
  • RemoveAttributes(): Removes the element's attributes.
  • ReplaceNodes(): Delete child nodes.
  • Remove(): Remove the entire node or node collection
IEnumerable products = from e in ("Product")
                                    where ("ID").Value == "2"
                                    select e;
if (() &gt; 0)
{
    ().Remove();
}

("Product").Remove(); // Delete the first Product child element("Product").Remove(); // Delete all Product child elements
("Product", null); // Delete the first Product child element
("Product").SetElementValue("ProductID", 1); // Modify ProductID child elements("Product").SetElementValue("ProductID", null); // deleteProductIDSub-elements

4. Attribute operation

//Add attributes:(new XAttribute("ID", 1));

//Modify properties:("ID", 2);

//Delete attributes:("ID").Remove();

6. Use XPath to query

In order to use XPath query in LINQ XML, a namespace needs to be added. as follows:

using ;

Added namespace, the XNode class adds a series of extension methods. With these extension methods, we have two options to handle XML. Make our application a smooth portable.

  • CreateNavigator method, which allows us to create an XPathNavigator object from an existing XNode object.
  • The XPathEvaluate method allows calculation of XPath expressions on XNode.
  • The XPathSelectElement method returns the element of the first matching expression, and the XPathSelectElements method returns all matching expression elements.

In order to query the following XML data:

 <category name="Technical">
    <category name=".NET">
        <books>
            <book>CLR via C#</book>
            <book>Essential .NET</book>
         </books>
    </category>
     <category name="Design">
        <books>
             <book>Refactoring</book>
            <book>Domain Driven Design</book>
            <book>Patterns of Enterprise Application Architecture</book>
         </books>
     </category>
     <books>
         <book>Extreme Programming Explained</book>
         <book>Pragmatic Unit Testing with C#</book>
         <book>Head First Design Patterns</book>
     </books>
 </category>

How to query XML data using XPath:

XElement root = ("");
var books = from book in ("//book")
            select book;

foreach (XElement book in books)
{
    ((string)book);
}

7. XML conversion

1. Use XSLT to convert

string xsl =@"http:///1999/XSL/Transform'>Book Catalog by , ";

XElement books = ("");
XDocument output = new XDocument();
using (XmlWriter writer = ())
{
    XslCompiledTransform xslTransformer = new XslCompiledTransform();
    ((new StringReader(xsl)));
    ((), writer);
}
(output);

To reuse the conversion code, the conversion logic can be encapsulated into an extension method

public static class XmlExtensions
{
    public static XDocument XslTransform(this XNode node, string xsl)
    {
        XDocument output = new XDocument();
using (XmlWriter writer = ())
        {
            XslCompiledTransform xslTransformer = new XslCompiledTransform();
            ((new StringReader(xsl)));
            ((), writer);
        }
        return output;
    }
}

//Use this extension method("").XslTransform(xsl));

2. Use LINQ to XML to convert XML

XSL is not the only way to change the XML format (in the past it was the only practical way), but today, LINQ to XML provides a competitive option. To convert using LINQ to XML, you need a LINQ expression that uses projection. The trick is that the projection must return an XElement instead of anonymous type.

string xmlFile = ("");
XDocument doc = (xmlFile);
 
XDocument newDoc = new XDocument(
    new XDeclaration("1.0", "utf-8", "yes"),
    new XElement("Movies",
        from DVD in ("DVD")
        where (int)("ID") < 3
        select new XElement[]
        {
            new XElement ("Moive",
                new XAttribute("name", (string)("Title")),
                ("Star")
            )
        }
    )
);
 
string newFile = ("");
(newFile);

result:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Movies>
  <Moive name="The Matrix">
    <Star>Keanu Reeves</Star>
    <Star>Laurence Fishburne</Star>
  </Moive>
  <Moive name="Forrest Gump">
    <Star>Tom Hanks</Star>
    <Star>Robin Wright</Star>
  </Moive>
</Movies>

The syntax based on LINQ conversion is usually easier to understand and more precise than conversions using XSL stylesheets. You can also easily replace it with another IEnumable collection, including the result set obtained by LINQ to Entities, and then package it into another format XML document.

This is all about this article about Linq To XML in C#. I hope it will be helpful to everyone's learning and I hope everyone will support me more.