【问题标题】:Dealing with NameSpace while reading XML Doc在阅读 XML Doc 时处理 NameSpace
【发布时间】:2016-08-16 10:12:52
【问题描述】:

好的,这是我的问题,我编写了一些代码来从 FTP 服务器下载文件,然后处理 XML 文件。很长一段时间都很好,但现在 XML 文件有一个命名空间,我的代码不再有效。这是有问题的代码,它找到所有调用节点然后处理它们

    Public Shared Function ParseXMLAndSave(ByVal xmlContent As String) As Generic.List(Of CallDetailRecordDataType)

    Dim xmlDoc As New XmlDocument
    Try
        xmlDoc.LoadXml(xmlContent)
    Catch ex As Exception
        Throw New Exception("Failed to load xml content. " & ex.Message)
    End Try

    Dim nodes As XmlNodeList = xmlDoc.SelectNodes("File/CDRs/Call")
    If nodes.Count = 0 Then Throw New Exception("No data node [File/CDRs/Call] found")

    Dim list As New Generic.List(Of CallDetailRecordDataType)

    For temp As Integer = 0 To nodes.Count - 1
        Try
            Dim record As CallDetailRecordDataType = ParseMainNode(nodes(temp))
            list.Add(record)
            SaveCallRecord(record)

        Catch ex As Exception
            Trace.WriteLine("Failed to parse node. " & ex.Message)
        End Try

    Next

    Return list
End Function

那么,在我的 xml 文件现在有了 NameSpace 之后,我需要做什么才能再次找到这些节点?

命名空间在 XML 文档中如下所示

<File xmlns="http://www.metaswitch.com/cfs/billing/V1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" compatibility="2">

【问题讨论】:

    标签: xml vb.net xml-parsing


    【解决方案1】:

    见:How to Select XML Nodes with XML Namespaces from an XmlDocument?

    对于您的情况,代码应该是这样的。但是,如果没有您的 xml 文档,我将无法验证这一点。

        Dim xmlDoc As New XmlDocument
        Try
            xmlDoc.LoadXml(xmlContent)
        Catch ex As Exception
            Throw New Exception("Failed to load xml content. " & ex.Message)
        End Try
    
        'Create a namespace manager
        Dim nsmgr As New XmlNamespaceManager(xmlDoc.NameTable)
        'Add a default namespace.
        nsmgr.AddNamespace("", "http://www.metaswitch.com/cfs/billing/V1.0")
    
        'Pass the namespaces into the query
        Dim nodes As XmlNodeList = xmlDoc.SelectNodes("File/CDRs/Call", nsmgr)
        If nodes.Count = 0 Then Throw New Exception("No data node [File/CDRs/Call] found")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-12
      • 1970-01-01
      • 2011-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多