1

I have an XML document that I only need to get 2 values from. In the past, I have been able to do this very easily using an XDocument:

Example XML:

<?xml version="1.0" standalone="yes"?>
<Vehicles>
   <Truck>
     <Color>Blue</Color>
     <Make>General Motors</Make>
     <Weight>3000</Weight>
   </Truck>
</Vehicles>

If I wanted to access just the <Weight> of the <Truck>, I could do by:

Dim xdoc as XDocument = XDocument.Load("c:/example.xml")
Dim truckWeight as Integer = Integer.Parse(xdoc.<Vehicles>.<Truck>.<Weight>.Value)

...and I would be on my merry way. However, in this case, my XML document has a namespace at the beginning, like so:

<?xml version="1.0" standalone="yes"?>
<Vehicles xmlns="http://interweb.com/Vehicles.xsd">
   <Truck>
      <Color>Blue</Color>
      <Make>General Motors</Make>
      <Weight>3000</Weight>
   </Truck>
</Vehicles>

If I attempt to use the above lines to get truckWeight, .Value returns Nothing even though xdoc would appear to be populated using Visual Studio's text reader.

What can I do to be able to use the mentioned XDocument notation I have used previously while leaving the XML file unaltered? If this is not possible, what is the alternate way of accessing something like <Weight> in an XML file with a namespace?

Jonas
  • 240
  • 1
  • 15

2 Answers2

1

My solution would be to add the namespace xmlns to every element. In your example it would look like this:

Dim ns As XNamespace = "http://interweb.com/Vehicles.xsd"
Dim truckWeight As Integer = Integer.Parse(xdoc.Element(ns + "Vehicles").Element(ns + "Truck").Element(ns + "Weight").Value)

When this code is executed, truckWeight would hold the value 3000.

Sebastian Hofmann
  • 1,440
  • 6
  • 15
  • 21
  • Fantastic! This worked great, especially since I can simply get the namespace of whatever xml doc I working with using `xdoc.Root.Name.Namespace`. Thanks! – Jonas Jun 07 '18 at 14:51
0

I'm not familiar with the notation so I can't tell if it is possible or not to use this with namespaces.

Here's the alternative if you do not find the way:

Dim xNS As XNamespace = "http://interweb.com/Vehicles.xsd"
Weight = xDoc.Root.Element(xNS + "Truck").Element(xNS + "Weight").Value

Or

Weight = xDoc.Element(xNS + "Vehicles").Element(xNS + "Truck").Element(xNS + "Weight").Value

You need xNS + "Name" for every element, since you have default namespace in the document. xNS+"Name" will do implicit conversion to XName for you.

Similar answers:

https://stackoverflow.com/a/2998837/1486185

https://stackoverflow.com/a/16018466/1486185

PavlinII
  • 1,061
  • 1
  • 7
  • 12
  • Thank you for answering but this method seems to be a duplicate of Sebastian's answer, which I have already marked as correct. – Jonas Jun 07 '18 at 14:53