LINQ to XML - accessing descendants with a prefix

前端 未结 3 2177
太阳男子
太阳男子 2020-12-16 18:42

I have a sample xml file like this


Name
address
Zip

        
相关标签:
3条回答
  • 2020-12-16 19:30

    The prefix "vs" should be mapped to a namespace in the header of the XML document, eg:

    <FooDocument xmlns:vs="http://schemas.example.com/vs">
    

    Then you can select those elements with LINQ by using an XNamespace, like this:

    XNamespace vs = "http://schemas.example.com/vs";
    
    var names = myXDoc.Root.Descendants(vs + "Name");
    

    The XNamespace and XName types all support implicit conversion from strings.

    0 讨论(0)
  • 2020-12-16 19:38

    You need to know what the namespace is. That will have been declared earlier, with something like:

    xmlns:vs="http://some_url_here"
    

    You can query using XNamespace:

    XNamespace vs = "http://some_url_here";
    var names = doc.Descendants(vs + "Name")
                   .Select(x => (string) x)
                   .ToList();
    

    The + here is actually converting an XNamespace and a string to an XName.

    0 讨论(0)
  • 2020-12-16 19:38

    I know this post is really old but wanted to provide some additional information. I was directed to this question and answer while seeking help with a more complex xml file. My xml had several names spaces and had nested namespaces as well. I was able to solve my problem with the suggestions found at this link

    It was great help and wanted to post it here in case someone else ran into the same problem

    0 讨论(0)
提交回复
热议问题