【问题标题】:VB.NET add an element to the XML document with LINQ to XMLVB.NET 使用 LINQ to XML 向 XML 文档添加元素
【发布时间】:2010-03-17 13:22:04
【问题描述】:

我正在使用以下代码向现有 XML 文档添加一个元素:

        Dim theXMLSource As String = Server.MapPath("~/Demo/") & "LabDemo.xml"
    Dim nodeElement As XElement

    Dim attrAndValue As XElement = _
        <LabService>
            <ServiceType>
                <%= txtServiceType.Text.Trim %>
            </ServiceType>
            <Level>
                <%= txtLevel.Text.Trim %>
            </Level>
        </LabService>

    nodeElement.Add(New XElement(attrAndValue))
    nodeElement.Save(theXMLSource)

会出现这样的错误:

System.NullReferenceException: Object reference not set to an instance of an object.

Object reference not set to an instance of an object.

Error line: nodeElement.Add(New XElement(attrAndValue))

我调试了它,但我还没有得到错误。你能说明问题是什么吗?谢谢

【问题讨论】:

    标签: vb.net linq-to-xml


    【解决方案1】:

    您需要加载现有文件,如下所示:

    Dim theXMLSource As String = Server.MapPath("~/Demo/LabDemo.xml")
    Dim document As XDocument = XDocument.Load(theXMLSource)
    
    ...
    
    document.Root.Add(attrAndValue)
    document.Save(theXMLSource)
    

    【讨论】:

      【解决方案2】:

      你定义了 nodeElement 但在调用它的方法之前不要实例化它。

      【讨论】:

        【解决方案3】:

        你需要先实例化:

        Dim nodeElement As New XElement 
        

        【讨论】:

          【解决方案4】:

          “将 nodeElement 调暗为新的 XElement”

          实际上 New 不是 XElements 的有效方法。即使它通过了调试(我对此表示怀疑)也会导致未处理的过载

          就像 SLaks 所说,您可以打开现有文件 - (我认为该文件可能像您在帖子中所说的那样存在)。

          你可以使用

          document.Root.Add(attrAndValue)
          

          或

          Dim nodeElement As XElement = document.<theXMLroot>(0)
          
          nodeElement.Add(attrAndValue)
          

          紧随其后

          document.Save(theXMLSource)
          

          两者的工作方式相同。由于您使用的是文字,我想您可能想知道“第二种方式”它很有用,主要是因为您可以更改为要插入元素的位置。

          例如

          Dim nodeElement As XElement = document.<theXMLroot>.<parent>(0)
          

          或

          Dim nodeElement As XElement = document...<parent>(0)
          

          希望对你有帮助

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2015-04-03
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多