vb.netxmldocument

Read Xml nodes using XmlDocument without namespace


I need to parse and read an xml using vb.net 4.0 XmlDocument, the problem is that xml does not have namespace, I have a working code which uses XElement, but need to use XmlDocument and can't import Xml.Linq so XElement is not an option for me:

Dim MyXML As XElement = XElement.Load(MemoryStream)
Dim count As Integer = Integer.Parse(MyXML.@elementCount)
For Each MyXElement As XElement In MyXML.Elements
    Dim Components As String() = MyXElement.@OPFCategoryCopyBackgroundColor.Split()
    R = Single.Parse(Components(0).Substring(2))
    G = Single.Parse(Components(1).Substring(2))
    B = Single.Parse(Components(2).Substring(2))
    EName = MyXElement.@OPFCategoryCopyName
Next

And here's my Xml:

<?xml version="1.0" encoding="utf-8"?>
<categories elementCount="18">
  <category xml:space="preserve" OPFCategoryCopyBackgroundColor="r:0.57 g:0.48 b:0.82" OPFCategoryCopyName="Birthday"></category>
  <category xml:space="preserve" OPFCategoryCopyBackgroundColor="r:0.45 g:0.60 b:0.88" OPFCategoryCopyName="Blue category"></category>
  <category xml:space="preserve" OPFCategoryCopyBackgroundColor="r:0.92 g:0.79 b:0.40" OPFCategoryCopyName="Brown Category"></category>
  <category xml:space="preserve" OPFCategoryCopyBackgroundColor="r:0.63 g:0.26 b:0.80" OPFCategoryCopyName="Family"></category>
</categories>

Now, if I use XmlDocument Load/LoadXml how can I obtain elementCount number and OPFCategoryCopyBackgroundColor/OPFCategoryCopyName?

Any tip or help is greatelt appreciated. Thanks in advance.


Solution

  • This worked for me:

    Using ms as MemoryStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes("<?xml version=""1.0"" encoding=""utf-8""?><categories " ...))
        Dim doc as XmlDocument = new XmlDocument
        doc.Load(ms)
        
        Console.WriteLine("elementCount: " & doc.SelectSingleNode("/categories/@elementCount").Value)
        
        For Each el As XmlNode In doc.SelectNodes("/categories/category")
            Console.WriteLine("OPFCategoryCopyBackgroundColor: " & el.Attributes.GetNamedItem("OPFCategoryCopyBackgroundColor").Value)
        Next
    End Using
    

    with the output:

    elementCount: 18
    OPFCategoryCopyBackgroundColor: r:0.57 g:0.48 b:0.82
    OPFCategoryCopyBackgroundColor: r:0.45 g:0.60 b:0.88
    OPFCategoryCopyBackgroundColor: r:0.92 g:0.79 b:0.40
    ...
    

    If there were namespaces in the XML, then this question could be used.