简体   繁体   中英

How to serialize/deserialize xml when multiple elements have one child?

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();

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM