我正在尝试更新以下 XML文档中的元素: 这是代码: Dim xmldoc As XDocument = XDocument.Load(theXMLSource1) Dim ql As XElement = (From ls In xmldoc.Elements("LabService") _ Where CType(ls.Element("ServiceType"), String).Equ
这是代码:
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)
这是XML文件:
<?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>
但是,我收到此错误消息:
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")
你能告诉我这是什么问题吗?谢谢.
xdoc是文档本身,仅包含根元素.因此,xmldoc.Elements(“LabService”)不返回任何内容.您需要编写xmldoc.Root.Elements(“LabService”).
顺便说一句,编写Where子句的最佳方法是Where ls.Element(“ServiceType”).Value =“Scan”