使用SelectSingleNode选择XML节点

时间:2018-06-08 09:49:50

标签: xml vb.net

对于以下文件,我检查它是否有retourcodes后检索BSN元素。

XML文件1:

str.strip

为此,我使用以下代码:

<?xml version="1.0" encoding="UTF-8"?>
<Jw:Bericht xmlns:Jw="http://www.istandaarden.nl/ijw/2_2/jw304/schema" xmlns:Std="http://www.istandaarden.nl/ijw/2_2/basisschema/schema">
  <Jw:Clienten>
    <Jw:Client>
      <Jw:Bsn>123456789</Jw:Bsn>
      <Jw:RetourCodes>
        <Jw:RetourCode>0200</Jw:RetourCode>
      </Jw:RetourCodes>
    </Jw:Client>
  </Jw:Clienten>
</Jw:Bericht>

现在我也收到了类似的XML文件,但结构略有不同(例如缺少Jw:前缀)。是否可以使用相同的代码从两个文件中检索BSN元素?

XML文件2:

Public Shared Function GetBSN() as String
  Dim XmlDocument As New Xml.XmlDocument()
  XmlDocument.XmlResolver = Nothing
  XmlDocument.Load("File.xml")

  Dim NSM As New Xml.XmlNamespaceManager(XmlDocument.NameTable)
  NSM.AddNamespace("Jw", "http://www.istandaarden.nl/ijw/2_2/jw304/schema")
  NSM.AddNamespace("Std", "http://www.istandaarden.nl/ijw/2_2/basisschema/schema")

  Dim RetourNodeList As Xml.XmlNodeList = XmlDocument.SelectNodes("//Jw:RetourCode", NSM)
  For i As Integer = 0 To RetourNodeList.Count
    If (Not RetourNodeList(i) Is Nothing) Then
      Dim Retournode As Xml.XmlNode = RetourNodeList(i)
      Dim Retourvalue As String = Retournode.InnerText
      Dim Parent As Xml.XmlNode = Retournode.ParentNode.ParentNode
      If (Parent.Name.Contains(":Client")) Then
        Dim BSN As String = GetNodeValue("Jw:Bsn", Parent, NSM)
        Return BSN
      End If
    End If
  Next
  Return Nothing
End Function

Public Shared Function GetNodeValue(Path As String, XmlDocument As Xml.XmlNode, NSM As Xml.XmlNamespaceManager) As String
  Dim Node As Xml.XmlNode = XmlDocument.SelectSingleNode(Path, NSM)
  If (Not Node Is Nothing) AndAlso (Not Node.InnerText Is Nothing) Then
    Return Node.InnerText
  Else
    Return ""
  End If
End Function

0 个答案:

没有答案