Updating an XML Element from LINQ to XML in VB.NET

I am trying to update an element in an XML document below:

Here is the code:

Dim xmldoc As XDocument = XDocument.Load(theXMLSource1) Dim ql As XElement = (From ls In xmldoc.Elements("LabService") _ Where CType(ls.Element("ServiceType"), String).Equals("Scan") _ Select ls.Element("Price")).FirstOrDefault ql.SetValue("23") xmldoc.Save(theXMLSource1) 

Here's the XML file:

 <?xml version="1.0" encoding="utf-8"?> <!--Test XML with LINQ to XML--> <LabSerivceInfo> <LabService> <ServiceType>Copy</ServiceType> <Price>1</Price> </LabService> <LabService> <ServiceType>PrintBlackAndWhite</ServiceType> <Price>2</Price> </LabService> </LabSerivceInfo> 

But I got this error message:

 Object reference not set to an instance of an object. Exception Details: System.NullReferenceException: Object reference not set to an instance of an object. Error line:ql.SetValue("23") 

Can you show me what the problem is? Thanks.

+4
source share
1 answer

xdoc is the document itself and contains only the root element. Therefore xmldoc.Elements("LabService") returns nothing.

You need to write xmldoc.Root.Elements("LabService") .

By the way, the best way to write a Where clause is Where ls.Element("ServiceType").Value = "Scan"

+4
source

Source: https://habr.com/ru/post/1304195/


All Articles