VB.NET add an element to the XML document with LINQ to XML
I'm adding an element to existing XML doc with the following code:
Dim theXMLSource As String = Server.MapPath("~/Demo/") & "LabDemo.xml"
Dim nodeElement As XElement
Dim attrAndValue As XElement = _
<开发者_如何学Go;LabService>
<ServiceType>
<%= txtServiceType.Text.Trim %>
</ServiceType>
<Level>
<%= txtLevel.Text.Trim %>
</Level>
</LabService>
nodeElement.Add(New XElement(attrAndValue))
nodeElement.Save(theXMLSource)
It makes error like this:
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))
I debugged it but I couldn't get the error yet. Can you show what the problem is? Thank you
You need to load the existing file, like this:
Dim theXMLSource As String = Server.MapPath("~/Demo/LabDemo.xml")
Dim document As XDocument = XDocument.Load(theXMLSource)
...
document.Root.Add(attrAndValue)
document.Save(theXMLSource)
You define nodeElement but then do not instantiate it before you call its methods.
You need to instantiate first:
Dim nodeElement As New XElement
"Dim nodeElement As New XElement"
Actually New is not a valid method for XElements. Even if it passes the debug (which I doubt it) it will result in an unhandled overload
Like SLaks said, you can open the existing file - (I reckon the file probably exists like you said in the post).
You can either use
document.Root.Add(attrAndValue)
or
Dim nodeElement As XElement = document.<theXMLroot>(0)
nodeElement.Add(attrAndValue)
followed by
document.Save(theXMLSource)
both work the same way. since you're using literals, I thought you might want to know the "second way" It's useful mainly because you can change to the where you want to insert the element.
for instance
Dim nodeElement As XElement = document.<theXMLroot>.<parent>(0)
or
Dim nodeElement As XElement = document...<parent>(0)
hope it helps
精彩评论