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")
Question
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")
OTHER TIPS
It is necessary to use XmlNamespaceManager. Let's suppose that your xml is in myfile.xml
. Name spaces are missing in your code so I used Microsoft ones instead.
Dim reader As New XmlTextReader("myfile.xml")
Dim doc As New XmlDocument()
doc.Load(reader)
Dim nsmanager As New XmlNamespaceManager(doc.NameTable)
nsmanager.AddNamespace("nc", "www.microsoft.com/books")
nsmanager.AddNamespace("default", "www.microsoft.com/store")
Dim book as XmlNode
Dim root as XmlElement = doc.DocumentElement
book = root.SelectSingleNode("//nc:ID", nsmanager)
Code is built from MS samples and was never run. Please apologize mistakes.
For more information see:
Manage Namespaces Using the XmlNamespaceManager
XmlNode.SelectSingleNode