VB.NET覚書

VB.NETの覚書
[個人メモ] [仕事メモ] [アイデア] [Ruby]
[TIPS] [対応表] [コメント書き方] [.NET Tips] [VB中学校] [VB.NET の入門サイト] [VB.NET コーディング標準 ] [VBレスキュー] [NonSoft]

2017-05-23

XML読み込み


Imports System.Xml

Public Class Form1

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click

        Dim myXmlDocument As XmlDocument = New XmlDocument()

        myXmlDocument.Load("C:\PROJECT\VB2010\xml\test.xml")

        Dim node As XmlNode

        node = myXmlDocument.DocumentElement
        displaytree(node)


    End Sub

    Public Sub DisplayTree(node As XmlNode)
        If Not IsNothing(node) Then Format(node)

        If node.HasChildNodes Then
            node = node.FirstChild
            While Not IsNothing(node)
                DisplayTree(node)
                node = node.NextSibling
            End While
        End If
    End Sub

    Private Sub Format(node As XmlNode)

        If Not node.HasChildNodes Then
            Debug.Print(Strings.Chr(9) & node.Name & "<" & node.Value & ">")
        Else
            Debug.Print(node.Name)

            If XmlNodeType.Element = node.NodeType Then
                Dim map As XmlNamedNodeMap = node.Attributes
                Dim attrnode As Object

                For Each attrnode In map
                    Debug.Print(" " & CType(attrnode, XmlNode).Name & "<" & CType(attrnode, XmlNode).Value & ">")
                Next
            End If
            Debug.Print("")
        End If
    End Sub

End Class

XML書き出し

参考にしたサイト

http://blog.syo-ko.com/?eid=1227

Imports System.Xml
Imports System.Text

Public Class Form1

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click

        Dim xEncode As Encoding = Encoding.GetEncoding(65001I) '65001がUTF8
        Dim xDocument As XmlDataDocument = New XmlDataDocument 'XMLドキュメント作成
        Dim xDeclaration As XmlDeclaration = xDocument.CreateXmlDeclaration("1.0", xEncode.BodyName, Nothing) 'ヘッダ部作成

        Dim xRoot As XmlElement = xDocument.CreateElement("ルート名")

        Call xDocument.AppendChild(xDeclaration)    'ヘッダー
        Call xDocument.AppendChild(xRoot)   'ルート

        Dim newNode As XmlElement = xDocument.CreateElement("子要素")
        Dim xValue As XmlText = xDocument.CreateTextNode("値")
        Dim newChild As XmlElement = xDocument.CreateElement("孫要素")

        Call newNode.AppendChild(newChild)

        'Call newNode.AppendChild(xValue)    '値を代入

        Call newNode.SetAttribute("属性名", "属性値")

        Call xRoot.AppendChild(newNode)  'ルートへ子要素を追加

        Call xDocument.Save("c:\temp\test.xml")

        xDeclaration = Nothing
        xRoot = Nothing
        xDocument = Nothing
        xEncode = Nothing


    End Sub
End Class
トラックバック - http://sub.g.hatena.ne.jp/garyo/20170523