0

I have a document with 20+ Elements & their attributes. I'm trying to update an attribute value and trying to using linq library to fetch the element and update its values. I have trouble finding the element from my XML Document, with the following logic.

VB.Net Code

Dim ProdID As String = "13737166A2A02"
Dim filePath = "D:\text.xml"
Dim xdoc As XElement = XElement.Load(filePath)
Dim elmnt As XElement = (From s In xdoc.Descendants("Parameter")
                         Where s.Element("name") = "ProductID"
                         Select s).FirstOrDefault()
elmnt.Element("value").SetValue(ProdID)
xdoc.Save(filePath)

XML Document:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Parameters>
   <Parameter name="ProductID" type="8" value="" autofill="False" />
   <Parameter name="ProductName" type="5" value="Leather Sneakers" autofill="False" />
   <Parameter name="ManufacturerID" type="5" value="100" autofill="False" />
   <Parameter name="Category" type="5" value="Sneakers" autofill="False" />
   <Parameter name="Color" type="White" value="Sneakers" autofill="False" />
</Parameters>

With the above code, my elmnt value is NULL on line 4, that results in a error on line 5 as 'Object reference not set to an instance of an object.'

Expected Output:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Parameters>
   <Parameter name="ProductID" type="8" value="13737166A2A02" autofill="False" />
   <Parameter name="ProductName" type="5" value="Leather Sneakers" autofill="False" />
   <Parameter name="ManufacturerID" type="5" value="100" autofill="False" />
   <Parameter name="Category" type="5" value="Sneakers" autofill="False" />
   <Parameter name="Color" type="White" value="Sneakers" autofill="False" />
</Parameters>

Any suggestions will be appreciate

1 Answers1

0

You want to use Attribute, not Element:

Dim elmnt As XElement = (From s In xdoc.Descendants("Parameter")
                         Where s.Attribute("name").Value = "ProductID"
                         Select s).FirstOrDefault()


If elmnt IsNot Nothing Then
    elmnt.Attribute("value").Value = ProdID
    xdoc.Save(filePath)
Else
    Console.WriteLine("Oops.")
End If

N.B. You should always use Option Strict On.

Andrew Morton
  • 24,203
  • 9
  • 60
  • 84