VB.NET Adds Element to XML Document with LINQ to XML

I am adding an element to an existing XML document with the following code:

        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)

This makes an error as follows:

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 still could not get the error. Can you show what the problem is? Thanks you

+3
source share
4 answers

You need to load an existing file, for example:

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

...

document.Root.Add(attrAndValue)
document.Save(theXMLSource)
+4
source

You define a nodeElement, but then do not create it before you call its methods.

0
source

:

Dim nodeElement As New XElement 
0

"Dim nodeElement As New XElement"

New XElements. ( ),

SLaks, - ( , , , , ).

you can 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 use literals, I thought you might need to know the "second way." This is useful mainly because you can jump to where you want to insert the item.

eg

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

or

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

hope this helps

0
source

Source: https://habr.com/ru/post/1736998/


All Articles