Search code examples
xmlvb.netxelement

Unable access elements inside Xelement directly


I have this XML inside an Xelement object called request:

    <?xml version="1.0" encoding="UTF-8"?>
<Message xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:nc="http://niem.gov/niem/niem-core/2.0">
    <List>
        <nc:Title/>
        <nc:Text/>
        <nc:Value/>
        <nc:ID>1234567890</nc:ID>
    </List>
</Message>

I can reach the value of the ID element by using:

request.Elements().Where(Function(e) e.Name.LocalName = "List").Value

However, this concatenates all the values of the elements inside the <List> element. According to what I have read, I should be able to get the value of an element by:

request.Element("ID")

...But I think the namespaces interfere. I am unable to directly query any of the four elements nested inside the List element. I have read several posts and tried several variations, but have had no luck. Please help :)

Example of reading xml into xelement and querying for ID which returns a value of Nothing:

 Dim tester As XElement = XElement.Load("C:\test.xml")
 Dim value As String = tester.Elements.Where(Function(e) e.Name.LocalName = "ID").Value

Solution

  • You have to use XNamespace instance:

    Dim doc = XDocument.Load("Input.txt")
    Dim nc = XNamespace.Get("http://niem.gov/niem/niem-core/2.0")
    
    Dim value = doc.Root.Element("List").Element(nc + "ID")