当多个元素有一个子元素时,如何序列化/反序列化 xml?

发布于 2025-01-01 09:10:23 字数 839 浏览 4 评论 0原文

我有一个 xml 文档,我必须对其进行反序列化。 该文档看起来像这样

<root>
  <node1>
    <node2>
      <child1>
        <infoNode1 attr="value"/>
                 .
                 .
                 .
      </child1>
      <child2>
         .
         .
      </child2> 
    </node2>
  </node1>
</root>

只有 child1 包含信息。我现在反序列化它的方式是,每个节点都有一个单独的类,但我喜欢只为 node2 有一个类,因为所有数据都包含在那里。

有没有简单的方法可以跳过/root/node1?我是否必须为此实施自己的反序列化?

谢谢。

编辑:

我用来执行反序列化的代码

string path = "file.xml";
RootClass projectDef = null;

XmlSerializer serializer = new XmlSerializer(typeof(RootClass));

StreamReader reader = new StreamReader(path);
projectDef = (RootClass)serializer.Deserialize(reader);
reader.Close();

I have one xml document which I have to deserialize.
The document looks something like this

<root>
  <node1>
    <node2>
      <child1>
        <infoNode1 attr="value"/>
                 .
                 .
                 .
      </child1>
      <child2>
         .
         .
      </child2> 
    </node2>
  </node1>
</root>

Only child1 contains information. The way I deserialize it now is that I have one separate class for each node, but I like to have just a class for node2 because all the data is contained there.

Is there any simple way to skip /root/node1? Do I have to implement my own de-serialization for this?

Thanks.

EDIT:

The code I use to perform the deserialization

string path = "file.xml";
RootClass projectDef = null;

XmlSerializer serializer = new XmlSerializer(typeof(RootClass));

StreamReader reader = new StreamReader(path);
projectDef = (RootClass)serializer.Deserialize(reader);
reader.Close();

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

つ低調成傷 2025-01-08 09:10:23

序列化/反序列化用于写入和读取对象或对象层次结构。状态。所以你需要让所有节点都完全支持序列化。

但如果您只想读取 xml 并将其解析为对象,则不必使用序列化。

  • 您可以使用 LINQ for XML 来解析文件并创建新对象。
  • 您可以使用 XPath 选择 node2 元素并从节点迭代器创建新对象。
  • 您可以实现 IXmlSerialized 并跳过 ReadXml 和 WriteXml 上不需要的节点。

Serialization/deserialization is for writting and reading the object, or object hierarchy. state. So you need to have all the nodes to fully support serialization.

But if you just want to read xml and parse it into objects, you dont have to use serialization.

  • You can use LINQ for XML to parse the file and create new objects.
  • You can use XPath to select the node2 elements and create new objects from the node iterator.
  • You can implement IXmlSerializable and skip the unwanted nodes on ReadXml and WriteXml.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文