Can't use Descendants() or Elements() with xmlns

后端 未结 3 1901
执笔经年
执笔经年 2021-01-04 11:52

I\'m new to working with XML, and I\'ve encountered a weird problem while trying to get a specific tag from a spring.net configuration file. After trying to narrow down the

相关标签:
3条回答
  • 2021-01-04 12:19

    You need to search for tags in that namespace:

    XNamespace ns = "aaa";
    
    xmlFile.Descendants(ns + "B").ToList()
    
    0 讨论(0)
  • 2021-01-04 12:19

    You should specify the namespace when querying for the elements.

    You can use the GetDefaultNamespace method to avoid hard-coding it. It's also useful if you don't know what it is ahead of time.

    Example:

    var ns = xmlFile.GetDefaultNamespace();
    var nodes = xmlFile.Descendants(ns + "B").ToList();
    
    0 讨论(0)
  • 2021-01-04 12:33

    Just for completeness sake:

    var lst = doc.Descendants("{aaa}B").ToList();
    

    (what the other told is correct, but I wanted to give another option :-) )

    For ultra completeness-sake, if you want to search ignoring the namespace:

    var lst = doc.Descendants().Where(p => p.Name.LocalName == "B").ToList();
    
    0 讨论(0)
提交回复
热议问题