0

XMLファイルを作成しようとしています

<?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>

その出力を実現するために次の VB.NET コードを作成しましたが、SetAttribute トークンと無効な XML ドキュメントに関する例外が常に発生します。

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

例外が発生する理由はありますか? 上記の XML 出力を取得するにはどうすればよいですか?

4

1 に答える 1

2

XmlWriter.WriteElementString要素と値を書き込みます。それは使用するようなものです:

writer.WriteStartElement("name");
writer.WriteString("value");
writer.WriteEndElement();

つまり、作成した要素にあなたを置き去りにすることはありません。したがって、これの代わりに:

.WriteElementString("size", Math.Round(fi.Length / 1048576, 2) & "Mb")
.WriteAttributeString("bytes", fi.Length.ToString)

私はあなたが欲しいと思います:

.WriteStartElement("size")
.WriteAttributeString("bytes", fi.Length.ToString)
.WriteString(Math.Round(fi.Length / 1048576, 2) & "Mb")
.WriteEndElement()

ただし、個人的には、サイズが大きくなりすぎない限り、LINQ to XML を使用してすべてをメモリ内に作成したいと考えています。一般に、これは操作が簡単な API です。

于 2011-06-27T10:58:00.083 に答える