我正在使用以下代码向现有 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))
我调试了它,但我还没有得到错误。你能说明问题是什么吗?谢谢
最佳答案
您需要加载现有文件,如下所示:
Dim theXMLSource As String = Server.MapPath("~/Demo/LabDemo.xml")
Dim document As XDocument = XDocument.Load(theXMLSource)
...
document.Root.Add(attrAndValue)
document.Save(theXMLSource)
关于VB.NET 使用 LINQ to XML 向 XML 文档添加元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2447423/