我有以下XML文件:
<?xml version="1.0" encoding="utf-8"?>
<Transactions>
<Transaction>
<Datetime>2018-06-21T00:30:31</Datetime>
<Operator>50</Operator>
<Turn>5163</Turn>
<Class>4</Class>
<Type>1</Type>
<Payments>
<Methods>
<Method>2</Method>
<Currency>EUR</Moeda>
</Methods>
</Payments>
</Transaction>
<Transaction>
<Datetime>2018-06-20T00:00:31</Datetime>
<Operator>34</Operator>
<Turn>3143</Turn>
<Class>4</Class>
<Type>1</Type>
<Payments>
<Methods>
<Method>2</Method>
<Currency>EUR</Currency>
</Methods>
</Payments>
</Transaction>
</Transactions>
我想遍历每个“事务”并保存节点的值。我这样做的方式进入了第二个“事务”,但是当我执行SingleNode时,它总是向我显示第一个的值。 我有以下代码:
Dim oXML As New XmlDocument
Dim ArquivoXML As String = TextBox1.Text
oXML.Load(ArquivoXML)
Dim mgr As New XmlNamespaceManager(oXML.NameTable)
mgr.AddNamespace("df", oXML.DocumentElement.NamespaceURI)
For Each Transaction As XmlNode In oXML.SelectNodes("//df:Transaction", mgr)
invoice.Operator = Transaction.SelectSingleNode("//df:Transaction", mgr).ChildNodes(1).InnerText
invoice.PaymentMethod = Transaction.SelectSingleNode("//df:Methods", mgr).ChildNodes(0).InnerText
invoice.Currency = Transaction.SelectSingleNode("//df:Methods", mgr).ChildNodes(1).InnerText
Next
答案 0 :(得分:1)
Transaction.SelectSingleNode("//df:Transaction")
SelectSingleNode返回与XPath查询匹配的第一个Node;如果找不到匹配的节点,则返回null。因此,您要做的始终是查看第一个节点(在节点集合中)
基本上是这样:
For Each NODE In NodeCollection
something = NodeCollection(1) 'instead of 1,2,3...n
Next
您应该做的是:
Transaction.ChildNodes(1).InnerText 'transaction=NODE=NodeCollection(x)
出现问题时,应断点代码并进行检查。
我从未使用过XML,但我会这样做(希望它能奏效)
For Each Transaction As XmlNode In oXML.SelectNodes("//df:Transaction", mgr)
invoice.Operator = Transaction.SelectSingleNode("./df:Operator", mgr).InnerText
invoice.PaymentMethod = Transaction.SelectSingleNode(".//df:Method", mgr).InnerText
invoice.Currency = Transaction.SelectSingleNode(".//df:Currency", mgr).InnerText
Next
编辑:我得到以下输出:
50
2
EUR
34
2
EUR
是那些期望值吗?
答案 1 :(得分:0)
使用//...
,您可以选择具有给定名称的 all 个节点。因此,在每次迭代中,表达式都会再次求值,结果保持不变。要利用迭代,您必须使用指向当前节点的相对路径:
For Each Transaction As XmlNode In oXML.SelectNodes("/df:Transactions/df:Transaction", mgr)
invoice.Operator = Transaction.SelectSingleNode("df:Operator", mgr).ChildNodes(0).InnerText
invoice.PaymentMethod = Transaction.SelectSingleNode("df:Payments/df:Methods/df:Method", mgr).ChildNodes(0).InnerText
invoice.Currency = Transaction.SelectSingleNode("df:Payments/df:Methods/df:Currency", mgr).ChildNodes(0).InnerText
Next