0

I need to read data from an xml file that might have (may not always have) a xmlns attribute. I cant find the nodes because I will not know the prefix. I am new to XML, I have found several solutions including removing the xmlns attribute but it is not for the "new" method of accessing xml using xelement.

Public Function GetHeader(xmlFileName As String, ByRef ispies As Boolean, ByRef isaces As Boolean, ByRef pcdbversiondate As Date, ByRef vcdbversiondate As Date) As String
    Dim xmlDoc As XElement
    Dim xmlNodes As IEnumerable(Of XElement)
    Dim Headertext As String
    Dim header As IEnumerable(Of XElement)

    xmlDoc = XElement.Load(xmlFileName)
    xmlNodes = xmlDoc.Elements()

    If InStr(xmlDoc.Name.ToString, "PIES") > 0 Then
        ispies = True
    End If

    If InStr(xmlDoc.Name.ToString, "ACES") > 0 Then
        isaces = True

    End If
    header = From nm In xmlDoc.Elements("Header")
    Headertext = ""
    For Each ele As XElement In header
        For Each cn As XElement In ele.Descendants
            Headertext += cn.Name.ToString & "=" & cn.Value & vbCrLf
            If cn.Name.ToString = "VcdbVersionDate" Then
                vcdbversiondate = fixDate(cn.Value.ToString)
            End If
            If cn.Name.ToString = "PcdbVersionDate" Then
                pcdbversiondate = fixDate(cn.Value.ToString)
            End If
        Next

    Next
    GetHeader = Headertext

End Function 
djv
  • 15,168
  • 7
  • 48
  • 72
zapdbf
  • 107
  • 6
  • 1
    It would help if you showed an example of the file – djv Mar 09 '20 at 19:38
  • it's proprietary i can't share it. but if the xmlns attribute was gone my code works fine. I might have to resort to opening the file as a text stream and stripping out this attribute. save the file and reopen it. This would be wasteful . I was hoping for a more elegant solution. – zapdbf Mar 10 '20 at 10:51
  • The answers to [How to remove all namespaces from XML with C#?](https://stackoverflow.com/questions/987135/how-to-remove-all-namespaces-from-xml-with-c) might give you a solution. `LocalName` looks promising. – Andrew Morton Mar 10 '20 at 11:47
  • @zapdbf so change the names of the elements? This should be simple with serialization – djv Mar 10 '20 at 13:41
  • i don't have control over that. These element names are part of an established standard, from the auto industry. but the files that are being created can have custom namespaces attached modifying the element name. – zapdbf Mar 10 '20 at 15:42

1 Answers1

0

here is how i had to fix the problem. xelement has local name under name so xelement.name.localname i can get the name without the name space prefix. the query looks like this

 header = From nm In xmlDoc.Elements Where nm.Name.LocalName = "Header"

i can now get around namespace issues. The trick was trying to find access to the localname, in the older method it was under the root, it is now under name.

zapdbf
  • 107
  • 6