I try to create a XML file
<?xml version="1.0" encoding="utf-8"?>
<ebooks count="494">
.....
<ebook absolute_path="J:\eBooks\Apress - Pro ASP.NET 4 in VB 2010, Third Edition.Sep.2010.ENG.pdf">
<file>Apress - Pro ASP.NET 4 in VB 2010, Third Edition.Sep.2010.ENG.pdf</file>
<size bytes="40176052">40Mb</size>
<created datetime="25.12.2010 12:48:52">25.12.2010</created>
<location>J:\eBooks</location>
</ebook>
<ebook absolute_path="J:\eBooks\Apress - Pro PHP and jQuery.Jun.2010.pdf">
<file>Apress - Pro PHP and jQuery.Jun.2010.pdf</file>
<size bytes="12523132">12.5Mb</size>
<created datetime="10.07.2010 19:43:10">10.07.2010</created>
<location>J:\eBooks</location>
</ebook>
.....
</ebooks>
I wrote following VB.NET code to achieve that output, but I always get an exception about SetAttribute Token and unvalid XML document.
Dim xmlFileName As String = "J:\eBooks\report_" & DateAndTime.Now.ToShortDateString & ".xml"
Dim xmlSetting As XmlWriterSettings = New XmlWriterSettings()
xmlSetting.Indent = True
Dim xw As XmlWriter = XmlWriter.Create(xmlFileName, xmlSetting)
...
...
dim singleFile as String
Dim myPdfFiles() as String = Directory.GetFiles(<path_to_dir>, <pdf_files>, SearchOption.AllDirectories)
Try
xw.WriteStartDocument()
xw.WriteStartElement("ebooks")
xw.WriteAttributeString("count", myPdfFiles.Count.ToString)
For Each singleFile In myPdfFiles
Dim fi As New FileInfo(singleFile)
With xw
.WriteStartElement("ebook")
.WriteAttributeString("absolute_path", fi.FullName.ToString)
.WriteElementString("file", fi.Name.ToString)
.WriteElementString("size", Math.Round(fi.Length / 1048576, 2) & "Mb")
'Attribute BYTES for <size>....'
.WriteAttributeString("bytes", fi.Length.ToString) '<- EXCEPTION!!!!'
.WriteElementString("created", fi.CreationTime.ToShortDateString)
'xw.WriteAttributeString("datetime", fi.CreationTime) <- would throw exception too'
.WriteElementString("location", fi.DirectoryName)
.WriteEndElement() '...close <ebook> element'
End With
Next
xw.WriteEndElement() '..close <ebooks> element'
xw.WriteEndDocument()
xw.Flush()
xw.Close()
Catch ex As Exception
MsgBox("Message : " & ex.Message)
End Try
Any Ideas why I get an exception? How do I get the XML-output as above ?
XmlWriter.WriteElementString
writes an element and a value. It's like using:
writer.WriteStartElement("name");
writer.WriteString("value");
writer.WriteEndElement();
In other words, it doesn't leave you within the element you create. So instead of this:
.WriteElementString("size", Math.Round(fi.Length / 1048576, 2) & "Mb")
.WriteAttributeString("bytes", fi.Length.ToString)
I think you want:
.WriteStartElement("size")
.WriteAttributeString("bytes", fi.Length.ToString)
.WriteString(Math.Round(fi.Length / 1048576, 2) & "Mb")
.WriteEndElement()
Personally though, I'd rather create the whole thing in memory using LINQ to XML, unless it's going to be too big. That's generally an easier API to work with.