none
How do I add and display attributes in an element? RRS feed

  • Question

  • Currently my function is only adding/displaying elements but not their attributes. I am not sure how to add attributes to the elements.

    I would like to have output that looks like this:

    <Transaction ReferenceNumber="CC-Add-Appl-Doc-06292015_05" Source="IntegrationBroker" TransactionType="Multi">
    	<DataPropagation>
    		<IntraTxn xPath="/TxnResponse/Result[1]/Codes/Code/CodeID" ReplStr="#|CODEID|#"/>
    	</DataPropagation>
    	<Message MessageType="GetCodeListing" NodeID="1" ReferenceNumber="R-19293" UserID="8304" Source="IntegrationBroker">
    		<CodeTypeID>JUS136</CodeTypeID>
    		<Search>
    			<Word ExactMatch='true'>07001G</Word>
    		</Search>
    	</Message>
    	<Message MessageType="GetJudicialOfficerCode" NodeID="1" ReferenceNumber="R-19293" UserID="8304" Source="IntegrationBroker">
    		<CodeID>#|CODEID|#</CodeID>
    	</Message>
    </Transaction>

    My function creates a new document and adds elements into it. I am not sure how to add attributes to the elements and that is the help I need.

     Function GetJudgeAPI(ByVal astrJudgeId As String) As XmlDocument
        Dim objXmlOutPutDoc As XmlDocument
        Dim objXmlTransactionDoc As XmlDocument
    
        'Create Transaction message
        objXmlTransactionDoc = New XmlDocument
        objXmlTransactionDoc.AppendChild(objXmlTransactionDoc.CreateElement("Transaction"))
        objXmlTransactionDoc.DocumentElement.SetAttribute("ReferenceNumber", System.Guid.NewGuid.ToString)
        objXmlTransactionDoc.DocumentElement.SetAttribute("Source", "IntegrationBroker")
        objXmlTransactionDoc.DocumentElement.SetAttribute("TransactionType", "Get Judge")
    
        'Add Data Propagation
        objXmlTransactionDoc.SelectSingleNode("Transaction").AppendChild(objXmlTransactionDoc.CreateElement("DataPropagation"))
        objXmlTransactionDoc.SelectSingleNode("Transaction/DataPropagation").AppendChild(objXmlTransactionDoc.CreateElement("IntraTxn"))
    
        'Add Message
        objXmlTransactionDoc.SelectSingleNode("Transaction").AppendChild(objXmlTransactionDoc.CreateElement("Message"))
        objXmlTransactionDoc.SelectSingleNode("Transaction/Message[1]").AppendChild(objXmlTransactionDoc.CreateElement("CodeTypeID"))
        objXmlTransactionDoc.SelectSingleNode("Transaction/Message[1]/CodeTypeID").InnerText = "JUS136"
        objXmlTransactionDoc.SelectSingleNode("/Transaction/Message[1]").AppendChild(objXmlTransactionDoc.CreateElement("Search"))
        objXmlTransactionDoc.SelectSingleNode("Transaction/Message[1]/Search").AppendChild(objXmlTransactionDoc.CreateElement("Word"))
        'Message 2
        objXmlTransactionDoc.SelectSingleNode("Transaction").AppendChild(objXmlTransactionDoc.CreateElement("Message"))
        objXmlTransactionDoc.SelectSingleNode("Transaction/Message[2]").AppendChild(objXmlTransactionDoc.CreateElement("CodeID"))
        objXmlTransactionDoc.SelectSingleNode("Transaction/Message[2]/CodeID").InnerText = "#|CODEID|#"
        Return (objXmlOutPutDoc)
    End Function

    Thursday, July 16, 2015 8:12 PM

Answers

  • I suggest that you use the XDocument as it is better in terms of performance than XMLDocument, you can check this article here also.

    I think also its more easier to manage from a syntax perspective, check the below examples:

    http://blogs.msmvps.com/deborahk/writing-to-an-xml-file-with-attributes/

    XElement.SetAttributeValue Method


    Fouad Roumieh

    Friday, July 17, 2015 5:57 AM
  • Hello,

    An alternate approach is to use xml literals with embedded expressions to create your document. In the following example I show creating the document with these where the end result if we were to save to a file or display to the IDE output window would look like this

    <Employees>
      <Employee id="1">
        <FirstName>Joan</FirstName>
        <LastName>Smith</LastName>
      </Employee>
      <Employee id="2">
        <FirstName>Mary</FirstName>
        <LastName>Adams</LastName>
      </Employee>
    </Employees>
    

    See comments in code and remember this is an example that shows the technique which you can adapt too. And lastly the data need not be from a DataTable, if you can write a LINQ query against your data then this can be done and if needed only one element rather than a collection can be done too.

    Imports System.Xml
    Module xmlLiterals
        ''' <summary>
        ''' Create mocked up data in a DataTable, take this data and create an XElement which we
        ''' then take and create both an XmlDocument and XDocument for you to pick from.
        ''' </summary>
        ''' <remarks></remarks>
        Public Sub Literals1()
            Dim dt As New DataTable With {.TableName = "MyTable"}
            dt.Columns.Add(New DataColumn With {.ColumnName = "Identifier", .DataType = GetType(Int32), .AutoIncrement = True, .AutoIncrementSeed = 1})
            dt.Columns.Add(New DataColumn With {.ColumnName = "FirstName", .DataType = GetType(String)})
            dt.Columns.Add(New DataColumn With {.ColumnName = "LastName", .DataType = GetType(String)})
    
            dt.Rows.Add(New Object() {Nothing, "Joan", "Smith"})
            dt.Rows.Add(New Object() {Nothing, "Mary", "Adams"})
    
            Dim Data As XElement =
                <Employees>
                    <%=
                        From T In dt
                        Select
                        <Employee id=<%= T.Field(Of Integer)("Identifier") %>>
                            <FirstName><%= T.Field(Of String)("FirstName") %></FirstName>
                            <LastName><%= T.Field(Of String)("LastName") %></LastName>
                        </Employee>
                    %>
                </Employees>
    
            Console.WriteLine(Data)
    
    
            ' Gives us a XDocument
            Dim xdoc As New XDocument(Data)
            ' Give us an XmlDocument
            Dim xmlDoc As XmlDocument = xdoc.ToXmlDocument
        End Sub
        ''' <summary>
        ''' Bypass creating a variable for the XElement
        ''' </summary>
        ''' <remarks></remarks>
        Public Sub Literals2()
            Dim dt As New DataTable With {.TableName = "MyTable"}
            dt.Columns.Add(New DataColumn With {.ColumnName = "Identifier", .DataType = GetType(Int32),
                                                .AutoIncrement = True, .AutoIncrementSeed = 1})
            dt.Columns.Add(New DataColumn With {.ColumnName = "FirstName", .DataType = GetType(String)})
            dt.Columns.Add(New DataColumn With {.ColumnName = "LastName", .DataType = GetType(String)})
    
            dt.Rows.Add(New Object() {Nothing, "Joan", "Smith"})
            dt.Rows.Add(New Object() {Nothing, "Mary", "Adams"})
    
            ' Gives us a XDocument
            Dim xdoc As New XDocument(
                <Employees><%= From T In dt Select
                    <Employee id=<%= T.Field(Of Integer)("Identifier") %>>
                        <FirstName><%= T.Field(Of String)("FirstName") %></FirstName>
                        <LastName><%= T.Field(Of String)("LastName") %></LastName>
                    </Employee> %>
                </Employees>)
            ' Give us an XmlDocument
            Dim xmlDoc As XmlDocument = xdoc.ToXmlDocument
    
        End Sub
        '
        ' The following are language extensions which are typically stored
        ' in their own module but put them here to you to learn the topic
        ' at hand and not worry about getting the extension methods done.
        '
    
        ''' <summary>
        ''' Concert a XDocument to a XmlDocument
        ''' </summary>
        ''' <param name="xDocument"></param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        <System.Runtime.CompilerServices.Extension> _
        Public Function ToXmlDocument(ByVal xDocument As XDocument) As XmlDocument
            Dim xmlDocument = New XmlDocument()
            Using xmlReader = xDocument.CreateReader()
                xmlDocument.Load(xmlReader)
            End Using
            Return xmlDocument
        End Function
        ''' <summary>
        ''' Convert an XmlDocument to a XDocument
        ''' </summary>
        ''' <param name="xmlDocument"></param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        <System.Runtime.CompilerServices.Extension> _
        Public Function ToXDocument(ByVal xmlDocument As XmlDocument) As XDocument
            Using nodeReader = New XmlNodeReader(xmlDocument)
                nodeReader.MoveToContent()
                Return XDocument.Load(nodeReader)
            End Using
        End Function
    End Module
    


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my webpage under my profile but do not reply to forum questions.

    Friday, July 17, 2015 2:50 PM
    Moderator

All replies

  • I suggest that you use the XDocument as it is better in terms of performance than XMLDocument, you can check this article here also.

    I think also its more easier to manage from a syntax perspective, check the below examples:

    http://blogs.msmvps.com/deborahk/writing-to-an-xml-file-with-attributes/

    XElement.SetAttributeValue Method


    Fouad Roumieh

    Friday, July 17, 2015 5:57 AM
  • Good advice but I am not sure how to do that. 
    Friday, July 17, 2015 1:47 PM
  • Hello,

    An alternate approach is to use xml literals with embedded expressions to create your document. In the following example I show creating the document with these where the end result if we were to save to a file or display to the IDE output window would look like this

    <Employees>
      <Employee id="1">
        <FirstName>Joan</FirstName>
        <LastName>Smith</LastName>
      </Employee>
      <Employee id="2">
        <FirstName>Mary</FirstName>
        <LastName>Adams</LastName>
      </Employee>
    </Employees>
    

    See comments in code and remember this is an example that shows the technique which you can adapt too. And lastly the data need not be from a DataTable, if you can write a LINQ query against your data then this can be done and if needed only one element rather than a collection can be done too.

    Imports System.Xml
    Module xmlLiterals
        ''' <summary>
        ''' Create mocked up data in a DataTable, take this data and create an XElement which we
        ''' then take and create both an XmlDocument and XDocument for you to pick from.
        ''' </summary>
        ''' <remarks></remarks>
        Public Sub Literals1()
            Dim dt As New DataTable With {.TableName = "MyTable"}
            dt.Columns.Add(New DataColumn With {.ColumnName = "Identifier", .DataType = GetType(Int32), .AutoIncrement = True, .AutoIncrementSeed = 1})
            dt.Columns.Add(New DataColumn With {.ColumnName = "FirstName", .DataType = GetType(String)})
            dt.Columns.Add(New DataColumn With {.ColumnName = "LastName", .DataType = GetType(String)})
    
            dt.Rows.Add(New Object() {Nothing, "Joan", "Smith"})
            dt.Rows.Add(New Object() {Nothing, "Mary", "Adams"})
    
            Dim Data As XElement =
                <Employees>
                    <%=
                        From T In dt
                        Select
                        <Employee id=<%= T.Field(Of Integer)("Identifier") %>>
                            <FirstName><%= T.Field(Of String)("FirstName") %></FirstName>
                            <LastName><%= T.Field(Of String)("LastName") %></LastName>
                        </Employee>
                    %>
                </Employees>
    
            Console.WriteLine(Data)
    
    
            ' Gives us a XDocument
            Dim xdoc As New XDocument(Data)
            ' Give us an XmlDocument
            Dim xmlDoc As XmlDocument = xdoc.ToXmlDocument
        End Sub
        ''' <summary>
        ''' Bypass creating a variable for the XElement
        ''' </summary>
        ''' <remarks></remarks>
        Public Sub Literals2()
            Dim dt As New DataTable With {.TableName = "MyTable"}
            dt.Columns.Add(New DataColumn With {.ColumnName = "Identifier", .DataType = GetType(Int32),
                                                .AutoIncrement = True, .AutoIncrementSeed = 1})
            dt.Columns.Add(New DataColumn With {.ColumnName = "FirstName", .DataType = GetType(String)})
            dt.Columns.Add(New DataColumn With {.ColumnName = "LastName", .DataType = GetType(String)})
    
            dt.Rows.Add(New Object() {Nothing, "Joan", "Smith"})
            dt.Rows.Add(New Object() {Nothing, "Mary", "Adams"})
    
            ' Gives us a XDocument
            Dim xdoc As New XDocument(
                <Employees><%= From T In dt Select
                    <Employee id=<%= T.Field(Of Integer)("Identifier") %>>
                        <FirstName><%= T.Field(Of String)("FirstName") %></FirstName>
                        <LastName><%= T.Field(Of String)("LastName") %></LastName>
                    </Employee> %>
                </Employees>)
            ' Give us an XmlDocument
            Dim xmlDoc As XmlDocument = xdoc.ToXmlDocument
    
        End Sub
        '
        ' The following are language extensions which are typically stored
        ' in their own module but put them here to you to learn the topic
        ' at hand and not worry about getting the extension methods done.
        '
    
        ''' <summary>
        ''' Concert a XDocument to a XmlDocument
        ''' </summary>
        ''' <param name="xDocument"></param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        <System.Runtime.CompilerServices.Extension> _
        Public Function ToXmlDocument(ByVal xDocument As XDocument) As XmlDocument
            Dim xmlDocument = New XmlDocument()
            Using xmlReader = xDocument.CreateReader()
                xmlDocument.Load(xmlReader)
            End Using
            Return xmlDocument
        End Function
        ''' <summary>
        ''' Convert an XmlDocument to a XDocument
        ''' </summary>
        ''' <param name="xmlDocument"></param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        <System.Runtime.CompilerServices.Extension> _
        Public Function ToXDocument(ByVal xmlDocument As XmlDocument) As XDocument
            Using nodeReader = New XmlNodeReader(xmlDocument)
                nodeReader.MoveToContent()
                Return XDocument.Load(nodeReader)
            End Using
        End Function
    End Module
    


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my webpage under my profile but do not reply to forum questions.

    Friday, July 17, 2015 2:50 PM
    Moderator