我用C ++编写了一个应用程序,它从类成员中生成一个XML文件。现在我想再次读取生成的文件,并将所有属性和值保存回C ++类。
我的XML编写器(写得很成功):
void TDescription::WriteXml( XmlWriter^ writer )
{
writer->WriteStartElement( "Description" );
writer->WriteAttributeString( "Version", m_sVersion );
writer->WriteAttributeString( "Author", m_sAuthor );
writer->WriteString( m_sDescription );
writer->WriteEndElement();
}
我的XML阅读器(导致异常):
void TDescription::ReadXml( XmlReader^ reader )
{
reader->ReadStartElement( "Description" );
m_sVersion = reader->GetAttribute( "Version" );
m_sAuthor = reader->GetAttribute( "Author" );
m_sDescription = reader->ReadString();
reader->ReadEndElement();
}
我生成的XML文件:
<?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>
以下是读者引起的例外情况:
An unhandled exception of type 'System.InvalidOperationException' occurred in System.Xml.dll
Additional information: There is an error in XML document (2, 2).
代码有什么问题?我认为XmlReader
方法没有以正确的方式使用!?
由于答案1,我更改了代码:
reader->ReadStartElement( "root" );
reader->ReadStartElement( "Description" );
m_sVersion = reader->GetAttribute( "Version" );
m_sAuthor = reader->GetAttribute( "Author" );
m_sDescription = reader->ReadString();
reader->ReadEndElement();
reader->ReadEndElement();
现在,我没有得到例外,m_sDescription
获得了正确的值,但 m_sVersion
和 m_sAuthor
仍然是空。
答案 0 :(得分:4)
您必须致电ReadStartElement
以获取&#34; root&#34;在那之前。
reader->ReadStartElement( "root" );
reader->ReadStartElement( "Description" );
修改:读取属性
reader->ReadToFollowing( "Description" );
reader->MoveToFirstAttribute();
String ^ m_sVersion = reader->Value;
reader->MoveToNextAttribute();
String ^ m_sAuthor = reader->Value;
String ^ m_sDescription = reader->ReadString();
reader->ReadEndElement();