gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 02:07:03 25 4
gpt4 key购买 nike

我用 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_sVersionm_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();

关于.net - 调用 XmlReader::ReadStartElement 时抛出 InvalidOperationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6858717/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com