Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

XElement is a class in C# that can be used to parse XML. Here is an example of how you can use XElement to parse an XML file:

First, read the XML file into a string variable:

string xmlString = File.ReadAllText(@"C:\example.xml");

Next, create an XElement object by parsing the XML string:

XElement root = XElement.Parse(xmlString);

You can now access the data in the XML file using the various properties of the XElement object. For example, to get the value of an element, you can use the Element method or the Descendants method:

string value = root.Element("TagName").Value;

Or:

string value = root.Descendants("TagName").FirstOrDefault()?.Value;

You can also iterate over the child elements of an XElement using the Elements method:

foreach (XElement childElement in root.Elements())
{
    // Do something with the child element
}

Finally, you can use the Attributes method to access the attributes of an element:

string attributeValue = root.Attribute("AttributeName").Value;