如何从以下xml获取每位客户的公司,名字,姓氏,手机,电子邮件,国家/地区,城市和邮政编码值?我尝试了以下代码,但是当缺少某些值时(例如第一条记录中的电子邮件),代码会从下一条记录中分配值,因此“ABCars”会获得“gwood@gmail.com”。
另外,您知道如何过滤加载的记录,以便只剩下另一个记录集中不存在手机号码的记录(记录集不包含在下面的代码中)?
Set xmlDoc = CreateObject("Msxml2.DOMDocument")
xmlDoc.async="false"
xmlDoc.setProperty "SelectionLanguage", "XPath"
xmlDoc.load("test.xml")
set nodes=xmlDoc.SelectNodes("//customer")
for i=0 to nodes.length-1
set company=xmlDoc.SelectNodes("//customer/company")
set firstname=xmlDoc.SelectNodes("//customer/firstname")
set lastname=xmlDoc.SelectNodes("//customer/lastname")
set mobile=xmlDoc.SelectNodes("//customer/mobile")
set email=xmlDoc.SelectNodes("//customer/email")
set country=xmlDoc.SelectNodes("//customer/address/country")
set city=xmlDoc.SelectNodes("//customer/address/city")
set zipcode=xmlDoc.SelectNodes("//customer/address/zipcode")
XML:
<?xml version="1.0" encoding="UTF-8"?>
<list>
<category>Cars</category>
<customers>
<customer>
<company>ABCars</company>
<firstname>Peter</firstname>
<lastname>Heinrich</lastname>
<mobile>9141453027</mobile>
<address>
<country>Germany</country>
<city>Berlin</city>
<zipcode>12345</zipcode>
</address>
</customer>
<customer>
<company>Best Cars</company>
<firstname>George</firstname>
<lastname>Wood</lastname>
<mobile>123456789</mobile>
<email>gwood@gmail.com</email>
<address>
<country>Great Britain</country>
<city>Leicaster</city>
<zipcode>67890</zipcode>
</address>
</customer>
</customers>
</list>
此致 Przemek
答案 0 :(得分:3)
您的循环遍历nodes
集合,但循环体查询每个迭代的整个文档,因此您每次都在进行相同的查询 - 使用返回的节点作为上下文节点来选择相对于该节点的节点:
set nodes=xmlDoc.SelectNodes("//customer")
for i=0 to nodes.length-1
' get the current node
set node = nodes(i)
' run xpath relative to the current node
set company = node.selectSingleNode("company")
set firstname = node.selectSingleNode("firstname")
set lastname = node.selectSingleNode("lastname")
set mobile = node.selectSingleNode("mobile")
set email = node.selectSingleNode("email")
set country = node.selectSingleNode("address/country")
set city = node.selectSingleNode("address/city")
set zipcode = node.selectSingleNode("address/zipcode")
next
如果XPath查询找不到任何节点,将返回Nothing
,您可以检查并适当路由:
set company = node.selectSingleNode("company")
if company is Nothing then
' do something if no company, eg break loop
exit for
end if
对于过滤,您可以构建XPath查询以仅选择那些不在该列表中的节点,例如
dim xpath: xpath = Empty
do until recordset.EOF
if xpath <> "" then
xpath = xpath & " and "
end if
xpath = xpath & "mobile != '" & recordset("mobile") & "'"
recordset.MoveNext
loop
if xpath <> "" then
xpath = "[" & xpath & "]"
end if
' eg you end up with something like "//customer[mobile != 123456789 and mobile != 987654321]"
set nodes = xmldoc.selectNodes("//customer" & xpath)