VB.Net/XML/DOM — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Текущая версия на 12:42, 26 мая 2010
Create new node from selected node
Public Class Example7
Shared Sub Main
Dim doc As System.Xml.XmlDocument
Dim editor As System.Xml.XPath.XPathNavigator
Dim writer As System.Xml.XmlWriter
doc = New System.Xml.XmlDocument()
doc.Load("pubs.xml")
editor = doc.CreateNavigator.SelectSingleNode("/pubs")
writer = editor.AppendChild()
writer.WriteStartElement("publishers")
writer.WriteAttributeString("pub_id", "1234")
writer.WriteAttributeString("pub_name", "new name")
writer.WriteEndElement()
writer.Close()
doc.Save("output.xml")
End Sub
End Class
Get Elements By Tag Name and Loop through Nodes
Imports System.Xml
Imports System.Xml.Serialization
Imports System.IO
Public Class MainClass
Public Shared Sub Main()
Dim rawData As String = _
"<Products>" & _
" <Product>" & _
" <name>Name 1</name>" & _
" <Id>101</Id>" & _
" <quantity>10</quantity>" & _
" </Product>" & _
" <Product>" & _
" <name>Name 2</name>" & _
" <Id>102</Id>" & _
" <quantity>10</quantity>" & _
" </Product>" & _
"</Products>"
Dim xmlDoc As New XmlDocument
Dim productNodes As XmlNodeList
Dim productNode As XmlNode
Dim baseDataNodes As XmlNodeList
Dim bFirstInRow As Boolean
xmlDoc.LoadXml(rawData)
productNodes = xmlDoc.GetElementsByTagName("Product")
For Each productNode In productNodes
baseDataNodes = productNode.ChildNodes
bFirstInRow = True
For Each baseDataNode As XmlNode In baseDataNodes
If (bFirstInRow) Then
bFirstInRow = False
Else
Console.Write(", ")
End If
Console.Write(baseDataNode.Name & ": " & baseDataNode.InnerText)
Next
Next
End Sub
End Class
Read Xml with XmlDocument and XmlNodeReader
Imports System.IO
Imports System.Xml
Public Class Form1
Public Shared Sub Main()
Dim doc As New XmlDocument()
doc.Load("c:\test.xml")
Dim r As XmlNodeReader = New XmlNodeReader(doc)
Dim ElementNumber As Integer
Do
ElementNumber += 1
System.Console.WriteLine(ElementNumber.ToString & ". " & r.NodeType.ToString)
If Not r.Name = "" Then System.Console.WriteLine(" Name: " & r.Name)
If Not r.Value = "" Then System.Console.WriteLine(" Value: " & r.Value)
If r.HasAttributes Then
Dim i As Integer
For i = 0 To r.AttributeCount - 1
r.MoveToAttribute(i)
System.Console.WriteLine("Attribute #" & (i + 1).ToString)
System.Console.WriteLine("Name: " & r.Name)
System.Console.WriteLine("Value: " & r.Value)
Next i
r.MoveToElement()
End If
Loop While r.Read() = True
End Sub
End Class