当前位置 : 主页 > 网页制作 > xml >

.net – 调用XmlReader :: ReadStartElement时抛出InvalidOperationException

来源:互联网 收集:自由互联 发布时间:2021-06-13
我在C中编写了一个应用程序,它从类成员中生成 XML文件.现在我想再次读取生成的文件,并将所有属性和值保存回C类. 我的XML编写器(写成功): void TDescription::WriteXml( XmlWriter^ writer ){ write
我在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仍为空.

在此之前,您必须为“root”调用ReadStartElement.

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();
网友评论