简体   繁体   English

vb.net中的xml解析

[英]xml parsing in vb.net

I have an xml formatted document that looks like this: 我有一个xml格式的文档,看起来像这样:

    <?xml version="1.0" encoding="windows-1250"?>
< Recipe>
  < Entry name="Stuffed Red Cabbage" ethnicity="Slavic" />
  < Cook_Time Hrs="1" Mins="30" />
  < Ingredients>
              < Cabbage Amount="1" Measurement="head" />
              < Egg Amount="1" Measurement="unit" />
              < Ground_Beef Amount="1" Measurement="lb" />
              < Margarine Amount="1/2" Measurement="cup" />
              < Onion Amount="1" Measurement="unit" />
              < Rice Amount="1" Measurement="cup" />
              < Tomato_Soup Amount="3" Measurement="cans" />
  < /Ingredients>
  < Description>core cabbage and boil until leaves start pulling away. Strip leaves and let cool.
chop onion and place in frying pan with margarine and heat till lightly browned.
put ground beef, rice, onion, egg and salt to taste in bowl and mix.
stuff each leaf with mixture.
put tomato soup and stuffed leaves in pot and cook for about an hour.</Description>
</Recipe>

and I have code that so far looks like this: 到目前为止,我的代码如下所示:

OpenFileDialog1.Filter = "RecipeBook files (*.rcp)|*.rcp"
    If OpenFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
        Try
            Dim settings As New XmlReaderSettings()
            settings.IgnoreComments = True
            Dim RecipeCard As String = OpenFileDialog1.FileName
                            Dim xmlreader As XmlTextReader
            xmlreader = New XmlTextReader(RecipeCard)
            Do While xmlreader.Read
                'needs to read xml and write appropriate items to database and listview
                xmlreader.MoveToContent()
                If xmlreader.Name.Equals("Entry") Then
                    MessageBox.Show(xmlreader.GetAttribute("name") & " " & xmlreader.GetAttribute("ethnicity"), "test")
                End If
                If xmlreader.Name.Equals("Cook_Time") Then
                    MessageBox.Show(xmlreader.GetAttribute("Hrs") & " hrs " & xmlreader.GetAttribute("Mins") & " mins", "test")
                End If
                If xmlreader.Name.Equals("Ingredients") Then

                End If
            Loop
        Catch
        End Try
    End If

My question has to do with parsing the Ingredients section. 我的问题与解析“成分”部分有关。 I was planning on doing something like this: 我正计划做这样的事情:

Dim IngredientCount As Integer = 0
Dim count As Integer = (something here that gets the count of subelements inside the Ingredients element)
                    For i = 1 To count
                    MessageBox.Show(xmlreader.GetAttribute("Amount") & " " & xmlreader.GetAttribute("Measurement"), "test")
                    Next

I just can't figure out how to get the number of subelements and then how to refer to each one in succession to get the name and then the attributes of that subelement. 我只是想不通如何获取子元素的数量,然后如何依次引用每个子元素来获取名称和子元素的属性。 Any suggestions would be greatly appreciated. 任何建议将不胜感激。

One of your comments indicates you are using the 3.5 framework. 您的评论之一表明您正在使用3.5框架。 If so then you can take advantage of XML literals to get your solution. 如果是这样,那么您可以利用XML文字获取解决方案。

Dim data = XDocument.Load(xmlReader)
Dim count = data.<Ingredients>.Elements().Count()

If you want to use the XmlTextReader then you can solve your problem by using ReadSubtree: 如果要使用XmlTextReader,则可以使用ReadSubtree解决问题:

If xmlreader.Name.Equals("Ingredients") Then
    Dim inner As XmlReader
    inner = xmlreader.ReadSubtree()
    inner.Read()
    While inner.Read
        If inner.IsStartElement Then
            MessageBox.Show(inner.GetAttribute("Amount") & " " & inner.GetAttribute("Measurement"), "test")
         End If
    End While
End If

It'd be easier though to not use XmlTextReader and instead use Linq to XML. 尽管不使用XmlTextReader而是使用Linq to XML会更容易。

What I've done for this in the past is call Read() to get each subelement in turn. 我过去为此所做的是调用Read()来依次获取每个子元素。 After each Read(), check that it's a start element. 在每个Read()之后,检查它是否是一个开始元素。 If it's not a start element then you've reached the end of the enclosing Ingredient tag and it's time to read the next one. 如果它不是开始元素,那么您已经到达了封闭的成分标签的末尾,现在该阅读下一个了。 The sample code in this documentation might be helpful: 本文档中的示例代码可能会有所帮助:

http://msdn.microsoft.com/en-us/library/xaxy929c.aspx http://msdn.microsoft.com/en-us/library/xaxy929c.aspx

XmlReader cannot give you the number of subelements of the current element because it reads one tag at a time. XmlReader无法提供当前元素的子元素数量,因为它一次读取一个标签。 It hasn't read those other elements yet so it doesn't know how many there are. 它还没有读取其他元素,所以它不知道有多少。 If you want to get more info on the XML tree while you're reading it, use XmlDocument. 如果要在阅读XML树时获取更多信息,请使用XmlDocument。 However, XmlDocument will read the whole file into memory at once before you even start processing it, whereas XmlReader reads the file from start to finish as you process it. 但是,XmlDocument会在甚至开始处理文件之前立即将整个文件读入内存,而XmlReader会在处理文件时从头到尾读取文件。 XmlReader should be faster and more memory-efficient. XmlReader应该更快,内存效率更高。

The sample here shows how to iterate over attributes if you don't know ahead of time which attributes an element will have: 如果您不提前知道元素将具有哪些属性,则此处的示例显示如何遍历属性:

http://msdn.microsoft.com/en-us/library/system.xml.xmlreader.movetonextattribute.aspx http://msdn.microsoft.com/en-us/library/system.xml.xmlreader.movetonextattribute.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM