LINQ to XML querying for sibling elements

It looks like you want to walk up the folder ancestor chain and accumulate the roles you find along the way. You can do that with the aptly-named Ancestors() and SelectMany() methods:

XElement fileFromMap = sitemap.Descendants("File").Where(
    file => file.Attribute("GUID").Value == guid.ToString("D")).Single();

XElement currentFile = new XElement("File",
    fileFromMap.Value,
    fileFromMap.Ancestors("Folder").SelectMany(
        folder => {
            XElement security = folder.Element("Security");
            return (security != null
                ? security.Elements("Role") : new XElement[0]);
        }));

EDIT: Changed element capitalization to match the updated question.

EDIT 2: The code above was mistakenly feeding a null item to SelectMany() (which is far less indulgent than XElement.Add() in this regard), and this resulted in a NullPointerException. It has been updated to return an empty XElement array instead.


Try this (I usually do Method syntax but you should be able to convert to query syntax)

        XElement currentFile = new XElement("File",
            sitemap.Descendants("file").Where(
               file => file.Attribute("GUID").Value.Equals(guid)).Select(
                   file => file.Parent.Element("security").Elements("role")));

Here currentFile should have

<File>
  <role>Admin</role>
</File>

Comments

  1. Raymond

    • 2018/6/20

    Example: Find an element named Book, and all sibling elements named First(); // LINQ to XML query IEnumerable<XElement> list1 = book .

  2. Durand

    • 2018/8/10

    Try this (I usually do Method syntax but you should be able to convert to query syntax) XElement currentFile = new XElement("File", sitemap.Descendants("file").Where( file => file.Attribute("GUID").Value.Equals(guid)).Select( file => file.Parent.Element("security").Elements("role")));

  3. Gonzales

    • 2018/3/10

    It looks like you want to walk up the folder ancestor chain and accumulate the roles you find along the way.

  4. Kase

    • 2016/7/10

    Example: Find an element named Book, and all sibling elements named Book. This example first finds a Book element in XML document Sample XML file: Books, and then finds all sibling elements named Book. The resulting collection includes the context node. The XPath expression is ../Book

  5. Graham

    • 2016/9/26

    var root = XElement.Parse(xmlString); var title = "Hansel and Gretel"; var query = root .Elements("Book") 

  6. Marku

    • 2016/9/24

    XElement co = XElement.Load("CustomersOrders.xml"); XElement add = co.Element("Customers").Element("Customer").Element("FullAddress"); // LINQ to XML query IEnumerable<XElement> list1 = add.ElementsBeforeSelf(); // XPath expression IEnumerable<XElement> list2 = add.XPathSelectElements("preceding-sibling::*"); if (list1.Count() == list2.Count() && list1.Intersect(list2).Count() == list1.Count()) Console.WriteLine("Results are identical"); else Console.WriteLine("Results differ"); foreach

  7. Turner

    • 2016/6/7

    IEnumerable<XElement>.AncestorsAndSelf* -> IEnumerable<XElement>. Query direct child elements. XDocument.Root-> XElement; XContainer.Element -> 

  8. Tristen

    • 2019/1/30

    Shows how to use the Let clause to calculate intermediate values in a LINQ to XML query. How to write a query that finds elements based on context (C#) Shows how to select elements based on other elements in the tree. How to debug empty query results sets (C#) Shows the appropriate fix when debugging queries on XML that is in a default namespace.

  9. Brown

    • 2021/1/3

    LINQ to XML querying for sibling elements. Sorry if this question is very basic, I have an XML sitemap that is structured like a directory tree:

  10. Marvin

    • 2018/3/27

    The most important advantage of LINQ to XML is its integration with Language-Integrated Query (LINQ). This integration enables you to write queries on the in-memory XML document to retrieve collections of elements and attributes. The query capability of LINQ to XML is comparable in functionality (although not in syntax) to XPath and XQuery.

  11. Benjamin

    • 2017/2/21

    This gets the value of the first <value> element after the first <key> element containing "SECOND_WANTED_KEY" : XDocument doc; string result 

  12. Albert

    • 2021/1/1

    For detailed information about using these extension methods, see System.Xml.XPath.Extensions. Unless you have a very specific reason for querying using XPath, such as extensive use of legacy code, using XPath with LINQ to XML isn't recommended. XPath queries won't perform as well as LINQ to XML queries.

  13. Kaleb

    • 2020/5/23

    The XElement class represents a DOM element node—an XML document is The XDocument's Elements method can return all child elements, or only elements.

  14. Alessandro

    • 2015/11/2

    # 17. Add a new Element at runtime using LINQ to XML VB.NET (Converted Code) Dim xEle As XElement = XElement.Load("..\..\Employees.xml") xEle.Add(New XElement("Employee", _ New XElement("EmpId", 5), _ New XElement("Name", "George"))) Can you expand on this and show how to add finish adding all the nodes for the employee.

  15. Rocky

    • 2019/10/7

    using System;/*from w w w . j a v a 2s. c o m*/ using System.IO; using System.Xml; using System.Xml.Linq; using System.Collections; using System.

  16. Dario

    • 2016/2/9

    В формате запроса это эквивалентно двум предложениям from : var query = new XElement(root, from p in xml.Elements(node) from a in

  17. Logan

    • 2020/1/17

    Return the collection of sibling elements after this node in document order.(Inherited from XNode.) ElementsAfterSelf(XName), Return a collection of filtered 

Comments are closed.

Recent Posts