Aug
21
Written by:
Steve Gray
8/21/2010 11:40 AM
Today’s task has to do with an XML document that has the form:
<OutboundReports>
<InvoiceNotice>
<InvoiceNoticeHeader InvoiceDate="20100607" InvoiceType="Invoice" invoiceID="60252726" purpose="PR">
</InvoiceNoticeHeader>
</InvoiceNotice>
<InvoiceNotice>
<InvoiceNoticeHeader InvoiceDate="20100607" InvoiceType="Invoice" invoiceID="60252727" purpose="PR">
</InvoiceNoticeHeader>
</InvoiceNotice>
</OutboundReports>
We need to move the InvoiceDate, InvoiceType, and invoiceID attributes to ‘nodes’, so that our integration program will see them, the current version will not read attributes. Here’s what we want it to look like in the end:
<OutboundReports>
<InvoiceNotice>
<InvoiceNoticeHeader InvoiceDate="20100607" InvoiceType="Invoice" invoiceID="60252726" purpose="PR">
<InvoiceDate>20100607</InvoiceDate>
<InvoiceType>Invoice</InvoiceType>
<InvoiceID>60252726</InvoiceID>
</InvoiceNoticeHeader>
</InvoiceNotice>
<InvoiceNotice>
<InvoiceNoticeHeader InvoiceDate="20100607" InvoiceType="Invoice" invoiceID="60252727" purpose="PR">
<InvoiceDate>20100607</InvoiceDate>
<InvoiceType>Invoice</InvoiceType>
<InvoiceID>60252726</InvoiceID>
</InvoiceNoticeHeader>
</InvoiceNotice>
</OutboundReports>
Here’s the code:
'Load the document
Dim xmlDoc As New XmlDocument
xmlDoc.Load(txtSourceFile.Text)
'loop through the xml document
Dim elemList As XmlNodeList = xmlDoc.GetElementsByTagName("InvoiceNoticeHeader")
Dim i As Integer
Dim MyCultureInfo As System.Globalization.CultureInfo = New System.Globalization.CultureInfo("en-US")
For i = 0 To elemList.Count - 1
Dim strInvoiceDate As String = elemList(i).Attributes("InvoiceDate").InnerXml
Dim dtInvoiceDate As Date = Date.ParseExact(strInvoiceDate, "yyyyMMdd", MyCultureInfo)
Dim xelemInvoiceDate As XmlElement = xmlDoc.CreateElement("InvoiceDate")
xelemInvoiceDate.InnerText = strInvoiceDate
elemList(i).AppendChild(xelemInvoiceDate)
Dim strInvoiceType As String = elemList(i).Attributes("InvoiceType").InnerXml
Dim xelemrInvoiceType As XmlElement = xmlDoc.CreateElement("InvoiceType")
xelemrInvoiceType.InnerText = strInvoiceType
elemList(i).AppendChild(xelemrInvoiceType)
Dim strInvoiceID As String = elemList(i).Attributes("invoiceID").InnerXml
Dim xelemInvoiceID As XmlElement = xmlDoc.CreateElement("InvoiceID")
xelemInvoiceID.InnerText = strInvoiceID
elemList(i).AppendChild(xelemInvoiceID)
Next i
xmlDoc.Save(Me.txtDestinationFile.Text)