How to convert XElement to XDocument
Just pass the XElement to the constructor of XDocument: var xdoc = new XDocument(new XElement(“a”, “b”));
Just pass the XElement to the constructor of XDocument: var xdoc = new XDocument(new XElement(“a”, “b”));
Try this: var x = new XElement(“root”, new XElement(“name”, “AAA”), new XElement(“last”, “BBB”), new XElement(“children”, from c in family select new XElement(“child”, new XElement(“name”, “XXX”), new XElement(“last”, “TTT”) ) ) );
var xml = @”<User ID=””11″” Name=””Juan Diaz”” LoginName=””DN1\jdiaz”” xmlns=””http://schemas.microsoft.com/sharepoint/soap/directory/”” />”; var user = XElement.Parse(xml); var login = user.Attribute(“LoginName”).Value; // “DN1\jdiaz”
Use XElement.Parse method like below XElement xmlTree = XElement.Parse(“<Root><Child>Hey</Child></Root>”); Console.WriteLine(xmlTree);
The extensions methods: public static class XExtensions { /// <summary> /// Get the absolute XPath to a given XElement /// (e.g. “/people/person[6]/name[1]/last[1]”). /// </summary> public static string GetAbsoluteXPath(this XElement element) { if (element == null) { throw new ArgumentNullException(“element”); } Func<XElement, string> relativeXPath = e => { int index = e.IndexPosition(); string name = e.Name.LocalName; … Read more
The immediate child elements of one XElement are accessible by calling the Element() or Elements() functions. Use the overloads with a name to access specific elements, or without to access all child elements. There are also similar methods like Attribute() and Attributes() that you might find useful.
To use XPath with LINQ to XML add a using declaration for System.Xml.XPath, this will bring the extension methods of System.Xml.XPath.Extensions into scope. In your example: var value = (string)xml.XPathEvaluate(“/response/data/hash”);
I wanted to see which of these suggested solutions performed best, so I ran some comparative tests. Out of interest, I also compared the LINQ methods to the plain old System.Xml method suggested by Greg. The variation was interesting and not what I expected, with the slowest methods being more than 3 times slower than … Read more