Elias Wick
Elias Wick

Reputation: 493

XML append attribute without creating a variable

I am trying to achieve the following code in one line without declaring a variable. The code will create an XML element, add an attribute and a value and finally append it to the XML document:

    Dim XMLDoc As New XmlDocument
    Dim XMLRoot As XmlElement
    XMLRoot = XMLDoc.CreateElement("Test1")
    XMLRoot.Attributes.Append(XMLDoc.CreateAttribute("Test2")).Value = "Test3"
    XMLDoc.AppendChild(XMLRoot)

I have tried the following but it returns an error: Boolean cannot be converted to 'XmlNode'.

    Dim XMLDoc As New XmlDocument
    XMLDoc.AppendChild(XMLDoc.CreateElement("Test1").Attributes.Append(XMLDoc.CreateAttribute("Test2").Value = "Test3"))

This returns error: Expression does not produce a value.

    Dim XMLDoc As New XmlDocument
    XMLDoc.AppendChild(XMLDoc.CreateElement("Test1").SetAttribute("Test2", "Test3"))

Upvotes: 0

Views: 236

Answers (2)

jdweng
jdweng

Reputation: 34421

I do not like the Library XML especially because of the number of lines you need to create and add elements. I exclusively use the new Net Library System.Xml.Linq. See code below :

Imports System.Xml
Imports System.Xml.Linq
Module Module1

    Sub Main()
        Dim doc As New XDocument(New XElement("Test1", New XAttribute("Test2", "Test3")))
    End Sub

End Module

Upvotes: 1

Fabio
Fabio

Reputation: 32445

It seems like you are creating new xml document. There are few other options to create xml without introducing "temporary" variables.

XDocument (System.Xml.Linq)

Dim document As New XDocument(
    new XElement(
        "root",
        new XElement(
            "element",
            new XAttribute("type", "parent")
        )
    )    
)

' Output

' <root>
'     <person type="parent" />
' </root>

With XML Literals which is a feature existing only in VB.NET you can do it in more convenient way

Dim document As XDocument = 
    <?xml version="1.0"?>
    <root>
        <person type="parent"></person>
    </root>

' Output

' <root>
'      <person type="parent" />
' </root>

If you need to append element into already existing xml:

With LINQ to XML

Dim document As XDocument = XDocument.Load(filepath)

document.Root.Add(new XElement("person", new XAttribute("type", "child")))

With XML Literals

Dim document As XDocument = XDocument.Load(filepath)

document.Root.Add(<person type="child"></person>)

Upvotes: 1

Related Questions