好的,所以这是我在这里发表的第二篇文章,我仍然忙于在vb.net中使用XML。
我知道如何获取具有唯一名称的单个元素所需的数据,但是如果该过程重复该怎么办?
我的例子,我正在使用API与工作中的程序进行交互。当我使用API运行搜索与商店#相关的票证时,它会返回多个值,如下所示:
<requests>
<request>
<form name="requestID">999999</form>
<form name="userTimeFormat">EEE, MMM d HH:mm:ss z yyyy</form>
<form name="contact">Contact Name</form>
<form name="status">Status</form>
<form name="statusID"></form>
<form name="priority"></form>
<form name="supportRep">Tom Smith</form>
<form name="supportRepCostPerHour">0.00</form>
<form name="createdTime">Time/Date</form>
<form name="updatedTime">Time/Date</form>
<form name="dueByTime">Time/Date</form>
<form name="isOverDue">T/F</form>
<form name="accountID"/>
<form name="account"/>
<form name="subject">Subject Goes Here</form>
</request>
<request>
<form name="requestID">999998</form>
<form name="userTimeFormat">EEE, MMM d HH:mm:ss z yyyy</form>
<form name="contact">Contact Name</form>
<form name="status">Status</form>
<form name="statusID"></form>
<form name="priority"></form>
<form name="supportRep">Tom Smith</form>
<form name="supportRepCostPerHour">0.00</form>
<form name="createdTime">Time/Date</form>
<form name="updatedTime">Time/Date</form>
<form name="dueByTime">Time/Date</form>
<form name="isOverDue">T/F</form>
<form name="accountID"/>
<form name="account"/>
<form name="subject"> Subject Goes Here </form>
</request>
因此,当我使用XPath获取信息时,它可以完美地用于第一个&lt;请求&gt;但我的问题是如何进入下一个&lt;请求&gt;获取下一组数据?
这是我的代码抓住它:
For Each requests As XElement In reader...<request>
Dim ReqID As String = reader.XPathSelectElement("//form[@name='requestID']")
Dim contact As String = reader.XPathSelectElement("//form[@name='contact']")
我知道我需要某种循环来重复这个过程但是现在我不知所措。任何和所有帮助/意见表示赞赏。我是编码和vb的新手,但我是一个快速而热切的学习者。感谢。
答案 0 :(得分:0)
您已经选择了<request>
元素;但是你必须在每个元素上使用XPath表达式,而不是根元素:
For Each r in xml.XPathSelectElements("//request")
Dim ReqID As String = r.XPathSelectElement(".//form[@name='requestID']")
Dim contact As String = r.XPathSelectElement(".//form[@name='contact']")
' ...do something... '
Next
或者,没有XPath:
For Each request in xml...<request>
Dim ReqID = request.<form>.Single(Function(f) f.@name = "requestID").Value
Dim contact = request.<form>.Single(Function(f) f.@name = "contact").Value
' ...do something... '
Next