I have the following XML File named Example.xml. Please note the namespace specification (xmlns) in the root element Message as the question below relates to this.
<?xml version="1.0" encoding="utf-8" ?>
<Message xmlns="http://www.myurl.com/Product" version="010" release="006">
<Header>
<To Qualifier="P" />
<From Qualifier="D" />
<MessageID>f244251a8c6c4070</MessageID>
<SentTime>2018-03-21T22:01:16.70Z</SentTime>
</Header>
<Body>
<Product>
<Description>
<Identification>
<ID1>1871598417</ID1>
<ID2>BE9432042-1234</ID2>
</Identification>
<Type>
<Name>Home Widget</Name>
<Category>Residential</Category>
</Type>
</Description>
</Product>
</Body>
</Message>
I have written the following function to return a string using LINQ
Public Function GetProductDetail() As String
Dim xDoc As XDocument = Nothing
Dim returnValue As String = ""
Using xr As XmlReader = XmlReader.Create("C:\Automation\Example.xml")
xDoc = XDocument.Load(xr)
Dim query = From t In xDoc.Descendants("Body")
Select New With {Key _
.ID1 = t.Element("Product").Element("Description").Element("Identification").Element("ID1").Value,
.ID2 = t.Element("Product").Element("Description").Element("Identification").Element("ID2").Value,
.Name = t.Element("Product").Element("Description").Element("Type").Element("Name").Value}
For Each item In query
returnValue = $"ID1: {item.ID1} | ID2: {item.ID2} | Name: {item.Name}"
Next
End Using
Return returnValue
End Function
The issue I am having is that the return value is blank with the above XML file.
When I change the root element to be only as follows:
<Message>
(i.e. remove everything including xmlns=....) I get the correct return value
returnValue = ID1: 1871598417 | ID2: BE9432042-1234 | Name: Home Widget
I have following questions:
What do I need add to my code or XPath Expression when the xmlns is part of the root element.
Sometime the XML file may not contain the ID2 Element. How do I check in the LINQ Query if the element does not exists or is this even possible with LINQ.
If this is not appropriate to do with LINQ can someone please provide code as to how this can be accomplished.
Appreciate everyone input, time and assistance.
Thanks
Juzer