代码之家  ›  专栏  ›  技术社区  ›  Tola

在vb.net中使用linq将xml元素更新为xml

  •  4
  • Tola  · 技术社区  · 16 年前

    我正在尝试更新以下XML文档中的元素:

    代码如下:

    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")
    

    你能告诉我是什么问题吗?谢谢您。

    1 回复  |  直到 16 年前
        1
  •  4
  •   SLaks    16 年前

    xdoc 是文档本身,并且只包含根元素。因此, xmldoc.Elements("LabService") 什么都不退货。

    你需要写 xmldoc.Root.Elements("LabService") .

    顺便说一下,写 Where 子句是 Where ls.Element("ServiceType").Value = "Scan"