Update XML element with LINQ to XML in VB.NET
I'm trying to update an element in the XML document below:
Here's 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&开发者_高级运维gt;
<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? Thank you.
xdoc
is the document itself and only contains the root element. Therefore, xmldoc.Elements("LabService")
doesn't return anything.
You need to write xmldoc.Root.Elements("LabService")
.
By the way, the best way to write the Where
clause is Where ls.Element("ServiceType").Value = "Scan"
精彩评论