Search code examples
vb.netxmlwriter

XmlTextWriter: Problems with WhiteSpace


I'm actually trying to use xmltextwriter to create a xml, but im having certains problems.

This is what i did

Dim writer As New XmlTextWriter("FactElec.xml", System.Text.Encoding.UTF8)
    writer.WriteStartDocument(False)
    writer.Formatting = Formatting.Indented
    writer.Indentation = 2
    writer.WriteStartElement("Invoice")

    writer.WriteStartElement("sac:AdditionalMonetaryTotal")
    writer.WriteElementString("cbc:id", "1001")
    writer.WriteWhitespace("/n")
    writer.WriteRaw("<cbc:PayableAmount currencyID=""PEN"">" + TotGrav + 
    "</cbc:PayableAmount>/n")
    writer.WriteEndElement()
    writer.WriteEndDocument()
    writer.Flush()
    writer.Close()

the problem is that i got an error in writer.WriteWhitespace, saying that it needs to be blank, but i need that the next WriteRaw appears in the next line. Just now it appears next to cbc:id

Thanks and sorry if i cannot explain it better.

Update: Or, just in case, if u know how can i add the currencyID=""PEN"" in cbc:PayableAmount, without using WriteRaw, could be better, because that is what is making me all these problems


Solution

  • You can use XML Literals for creating xml files in little bid cleaner way.

    Imports <xmlns:sac="http://yoursacnamespace">
    Imports <xmlns:cbc="http://yourcbcnamespace">
    
    Public Module XmlInvoiceHelper
        Public Sub SaveWithValue(totGrav As Integer)
            Dim xml As XElement =
            <Invoice>
                <sac:AdditionalMonetaryTotal>
                    <cbc:id>1001</cbc:id>
                    <cbc:PayableAmount currencyID="PEN"><%= totGrav %></cbc:PayableAmount>
                </sac:AdditionalMonetaryTotal>
            </Invoice>
    
            Using  writer As New XmlTextWriter("YourFile.xml", Encoding.UTF8)
                xml.Save(writer);
            End Using
        End Function
    End Module
    

    For namespaces sac and cbc you need add Imports line in the beginning of code file to support them for Xml literals code.