一、以下代码读取exp.xml;
1、n表示xml Element的嵌套层数,每进入一个嵌套n=n+1
2、m表示Attribute的次序
3、程序用来显示Element的嵌套关系。
4、去掉 <data date='2014-8-24' /> <data date='2014-9-24' /> 这二行,输出的嵌套关系是正常的,最后返回到{0}
5、遇到Xml文件中有短结尾 ‘/>' 的时候,(例如<date date = '2014-08-09' />),代码读不到EndElement ‘/>’ 嵌套关系就出错。
请教如何能够改这段程序,读取有 “/>"情况下的嵌套关系
Using reader As System.XML.XmlReader = System.XML.XmlReader.Create("exp.xml")
' Move the reader to the second book node.
reader.MoveToContent()
reader.ReadToDescendant("book")
'reader.Skip() 'Skip the first book.
' Parse the file starting with the second book node.
Dim n As Integer = 0
Do
Select Case reader.NodeType
Case System.XML.XmlNodeType.Element
n=n+1
output.show("<{" & n & "}" & reader.Name)
Dim m As Integer = 1
While reader.MoveToNextAttribute()
output.show(" {" & n & "}='{" & m & "}'"& reader.Name & ": " & reader.Value)
m=m+1
End While
output.show(">")
Case System.XML.XmlNodeType.Text
output.show(reader.Value)
Case System.XML.XmlNodeType.EndElement
output.show("</{" & n & "}>" & reader.Name)
n=n-1
End Select
Loop While reader.Read()
End Using
二、exp.xml:
<!--sample XML fragment-->
<bookstore>
<book genre='novel' ISBN='10-861003-324'>
<data date='2014-8-24' />
<title>The Handmaid's Tale</title>
<price>19.95</price>
</book>
<book genre='novel' ISBN='1-861001-57-5'>
<data date='2014-9-24' />
<title>Pride And Prejudice</title>
<price>24.95</price>
</book>
</bookstore>
三、运行结果:
<{1}bookstore
>
<{2}date
{2}='{1}'date: 2014-08-09
>
<{3}book
{3}='{1}'genre: novel
{3}='{2}'ISBN: 10-861003-324
>
<{4}title
>
The Handmaid's Tale
</{4}>title
<{4}price
>
19.95
</{4}>price
</{3}>book
<{3}date
{3}='{1}'date: 2014-09-09
>
<{4}book
{4}='{1}'genre: novel
{4}='{2}'ISBN: 1-861001-57-5
>
<{5}title
>
Pride And Prejudice
</{5}>title
<{5}price
>
24.95
</{5}>price
</{4}>book
</{3}>bookstore
[此贴子已经被作者于2014-8-25 16:19:39编辑过]