开发者

InvalidOperationException throw when calling XmlReader::ReadStartElement

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 va开发者_如何转开发lue but m_sVersion and m_sAuthor are still empty.


You have to call ReadStartElement for "root" before that.

reader->ReadStartElement( "root" );     
reader->ReadStartElement( "Description" );

Edit: Read attribute

reader->ReadToFollowing( "Description" );
reader->MoveToFirstAttribute();
String ^ m_sVersion = reader->Value;     
reader->MoveToNextAttribute();
String ^ m_sAuthor = reader->Value;           
String ^ m_sDescription = reader->ReadString();     
reader->ReadEndElement();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜