【问题标题】:Update XML element with LINQ to XML in VB.NET在 VB.NET 中使用 LINQ to XML 更新 XML 元素
【发布时间】:2010-03-16 04:08:22
【问题描述】:

我正在尝试更新以下 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")

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

【问题讨论】:

    标签: xml vb.net linq-to-xml


    【解决方案1】:

    xdoc 是文档本身,只包含根元素。因此,xmldoc.Elements("LabService") 不会返回任何内容。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-07
      相关资源
      最近更新 更多