Parsing xml files


  • I am trying to parse an xml file in a c++ Metro app.

    XmlDocument^ m_XMLDoc = ref new XmlDocument;

    m_XMLDoc->LoadFromFileAsync( m_XmlFile );

    XmlElement^ Elem = m_XMLDoc->DocumentElement;

    int x = Elem->ChildNodes->Size;The xml file is successfully loaded by LoadFromFileAync but i am not able to get the document element. Elem is null. My xml is as below: 




    I want to read all the items of each <Book> </Book> section. what could be wrong? I am missing something in my code..

    Thursday, May 24, 2012 3:05 PM


  • You aren't searching or iterating through the tree at all here. You can use xpath syntax to find all nodes matching a given path, or search for all nodes with a given name, etc.

    This is demonstrated in C# in the Windows Runtime XML data API sample

    Here's a quick code snippet to find the Books and then the Title and Price of each book:

    	XmlNodeList^ books = m_XMLDoc->GetElementsByTagName("Book");
    	for (unsigned int i=0 ; i < books->Size ; i++)
    		 XmlElement^ book = dynamic_cast<XmlElement^>(books->GetAt(i));
    		 auto titleNode = book->SelectSingleNode("Title");
    		 auto priceNode = book->SelectSingleNode("Price");
    		 String^ title = dynamic_cast<String^>(titleNode->FirstChild->NodeValue);
    		 String^ pricee = dynamic_cast<String^>(priceNode->FirstChild->NodeValue);

    • Proposed as answer by Jesse Jiang Friday, May 25, 2012 7:00 AM
    • Marked as answer by Jesse Jiang Friday, June 01, 2012 8:22 AM
    Friday, May 25, 2012 1:58 AM