I wrote an application in C++ which generates an XML file out of class members. Now I want to read the generated file again and save all attributes and values back to the C++ classes.
My XML writer (writes with success):
void TDescription::WriteXml( XmlWriter^ writer )
{
writer->WriteStartElement( "Description" );
writer->WriteAttributeString( "Version", m_sVersion );
writer->WriteAttributeString( "Author", m_sAuthor );
writer->WriteString( m_sDescription );
writer->WriteEndElement();
}
My XML reader (causes an exception):
void TDescription::ReadXml( XmlReader^ reader )
{
reader->ReadStartElement( "Description" );
m_sVersion = reader->GetAttribute( "Version" );
m_sAuthor = reader->GetAttribute( "Author" );
m_sDescription = reader->ReadString();
reader->ReadEndElement();
}
My generated XML file:
<?xml version="1.0" encoding="utf-8"?>
<root Name="database" Purpose="try" Project="test">
<!--Test Database-->
<Description Version="1.1B" Author="it">primary</Description>
</root>
Here is the exception caused by the reader:
An unhandled exception of type 'System.InvalidOperationException' occurred in System.Xml.dll
Additional information: There is an error in XML document (2, 2).
What’s the problem with the code? I think that the XmlReader methods were not used the right way!?
Due to answer 1, I have changed the code:
reader->ReadStartElement( "root" );
reader->ReadStartElement( "Description" );
m_sVersion = reader->GetAttribute( "Version" );
m_sAuthor = reader->GetAttribute( "Author" );
m_sDescription = reader->ReadString();
reader->ReadEndElement();
reader->ReadEndElement();
Now, I don’t get an exception and m_sDescription gets the right value but m_sVersion and m_sAuthor are still empty.
You have to call
ReadStartElementfor “root” before that.Edit: Read attribute