从内部 XML 节点进行 XML 反序列化
我正在努力将我的 .NET 对象序列化/反序列化。根据 XML 文件的要求,该对象必须位于名为 mycompany
的主节点内。这是该文件的示例:
<?xml version="1.0" encoding="utf-8"?>
<mycompany>
<station>
<serial>VAA008090067</serial>
</station>
</mycompany>
我在反序列化时遇到问题。我不知道如何告诉序列化器,“嘿,请确保在反序列化之前深入了解 mycompany
节点。”
这是我当前的反序列化代码(不考虑根节点):
Stream binaryStream = File.Open(Filename, FileMode.Open);
XmlSerializer xformatter = xformatter = new XmlSerializer(typeof(T));
obj = (T)xformatter->Deserialize(stream);
我尝试执行以下代码:创建一个 XmlTextStream
,读入文件头节点和 mycompany
节点,然后将流传递给序列化器
Stream binaryStream = File.Open(Filename, FileMode.Open);
xmlReader = gcnew XmlTextReader(binaryStream);
xmlReader.Read(); // add error checking
xmlReader.Read(); // add error checking
xformatter = gcnew XmlSerializer(T.typeid);
obj = (T)xformatter.Deserialize(xmlReader);
上面不起作用,抛出一个 XmlElement 错误:根元素丢失
。
我知道有一个简单的解决方案,但我无法找到它。
I'm working on getting my .NET object serialized / deserialized. As a requirement for our XML files, the object must be inside a master node named mycompany
. Here is an example for the file:
<?xml version="1.0" encoding="utf-8"?>
<mycompany>
<station>
<serial>VAA008090067</serial>
</station>
</mycompany>
I'm running into an issue getting this to deserialize. I'm not aware of how to tell the serializer, "Hey, make sure you dig into the mycompany
node before you deserialize."
Here is my current deserializtion code (not accounting for a root node):
Stream binaryStream = File.Open(Filename, FileMode.Open);
XmlSerializer xformatter = xformatter = new XmlSerializer(typeof(T));
obj = (T)xformatter->Deserialize(stream);
I attempted to do the following code: Create an XmlTextStream
, read in the file header node, and the mycompany
node, then pass the stream to the serializer
Stream binaryStream = File.Open(Filename, FileMode.Open);
xmlReader = gcnew XmlTextReader(binaryStream);
xmlReader.Read(); // add error checking
xmlReader.Read(); // add error checking
xformatter = gcnew XmlSerializer(T.typeid);
obj = (T)xformatter.Deserialize(xmlReader);
The above doesn't work, throws me an XmlElement error: Root element is missing
.
I know there is a simple solution, but I am unable to find it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将其更改为
Change it to