如何用LINQ to XML在VB.NET中高效更新XML元素?
- 内容介绍
- 文章标签
- 相关推荐
本文共计351个文字,预计阅读时间需要2分钟。
我正在尝试更新以下代码片段,尽量简化并去除冗余,不超过100个字:
尝试更新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(%27%27)
更新后的代码:
加载XML,筛选LabService元素,匹配ServiceTypeDim xmldoc=XDocument.Load(theXMLSource1)Dim ql=xmldoc.Elements(LabService).Where(ls=> ls.Element(ServiceType).Value==)
我正在尝试更新以下 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")
你能告诉我这是什么问题吗?谢谢.
xdoc是文档本身,仅包含根元素.因此,xmldoc.Elements(“LabService”)不返回任何内容.您需要编写xmldoc.Root.Elements(“LabService”).
顺便说一句,编写Where子句的最佳方法是Where ls.Element(“ServiceType”).Value =“Scan”
本文共计351个文字,预计阅读时间需要2分钟。
我正在尝试更新以下代码片段,尽量简化并去除冗余,不超过100个字:
尝试更新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(%27%27)
更新后的代码:
加载XML,筛选LabService元素,匹配ServiceTypeDim xmldoc=XDocument.Load(theXMLSource1)Dim ql=xmldoc.Elements(LabService).Where(ls=> ls.Element(ServiceType).Value==)
我正在尝试更新以下 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")
你能告诉我这是什么问题吗?谢谢.
xdoc是文档本身,仅包含根元素.因此,xmldoc.Elements(“LabService”)不返回任何内容.您需要编写xmldoc.Root.Elements(“LabService”).
顺便说一句,编写Where子句的最佳方法是Where ls.Element(“ServiceType”).Value =“Scan”

