尝试拆分字符串时出错

时间:2013-08-14 23:53:08

标签: .net vb.net string

我正在尝试拆分字符串,但是出现了错误:

ban = Microsoft.VisualBasic.Strings.Split(xml, "<item jid='", -1,
      Microsoft.VisualBasic.CompareMethod.Binary)

这是完整代码

Dim ban As String  
xml = xml.Replace("\\\", ")  
If (xml.IndexOf("<query xmlns='http://jabber.org/protocol/muc#admin'>") >= 0) Then  
    If (xml.IndexOf("affiliation='outcast'") >= 0) Then  
        xml = xml.Substring(xml.IndexOf("<item jid='") + 11)  
        xml = xml.Replace("' affiliation='outcast' /></query></iq>", "").Replace("' affiliation='outcast' />", "")  
        xml = xml.Replace("role='participant' />", "")  
        ban = Microsoft.VisualBasic.Strings.Split(xml, "<item jid='", -1, Microsoft.VisualBasic.CompareMethod.Binary)  
        ListBox2.Items.Clear()  
        For t = LBound(ban) To UBound(ban)  
            ListBox2.Items.Add(ban(t))  
            info.Text = "List ban Count {" + ListBox2.Items.Count + "}"  
        Next  
    End If  
End If 

1 个答案:

答案 0 :(得分:3)

好的......对可用代码段的一些研究将我引向this。因此,假设XML文档看起来像这样:

<iq from='kinghenryv@shakespeare.lit/throne'
    id='ban1'
    to='southampton@chat.shakespeare.lit'
    type='set'>
  <query xmlns='http://jabber.org/protocol/muc#admin'>
    <item affiliation='outcast'
          jid='earlofcambridge@shakespeare.lit'/>
  </query>
</iq>

请注意,XML可能比这更多,但它可以用于演示目的。使用字符串方法解析XML是很难的方法,IMO。使用XML API(如LINQ to XML)要容易得多。

以下是LNQ to XML的示例。

Dim xDoc = XDocument.Parse(xml)
Dim ns as XNamespace = "http://jabber.org/protocol/muc#admin"

Dim query = From x in xDoc.Descendants(ns + "item")
            Where x.Attribute("affiliation").Value = "outcast"
            Select x.Attribute("jid").Value

上面的代码将XML字符串加载到XDocument中。它还设置名称空间(包含在query元素中。

然后对XML进行查询。它收集属性为item且值为“outcast”的所有affiliation个节点,然后返回相应的jid值。

然后您可以像这样迭代集合:

For Each jid As String In query

    ListBox2.Items.Add(jid)   
Next

info.Text = "List ban Count {" + ListBox2.Items.Count.ToString() + "}"

已编辑添加

如果您仍然希望按照代码的方式执行此操作,请尝试以下更改:

Dim ban As String()

ban = Microsoft.VisualBasic.Strings.Split(xml, "<item jid='", -1, _
  Microsoft.VisualBasic.CompareMethod.Binary)

正如其他人所指出的那样,Split返回一个数组,并且已将ban定义为String而不是String()[array]。

相关问题