Deserializing the comments in XML file

前端 未结 2 1159
深忆病人
深忆病人 2021-01-21 04:33

I am trying to deserialize the following sample XML file.I have created the schema for this XML file.With the help of schema i am able to deserialize the XML into object.

<
相关标签:
2条回答
  • 2021-01-21 04:39

    The point of object serialization is to save the state of an object, and restore it later. Object fields are mapped to XML elements and attributes, and vice versa. XMLSerializer does not map anything to comments or vice versa, so you can't deserialize comments to anything in your object.

    However if you use an XmlReader (as @Amigable said) which you pass to the Deserialize() method, you can then use that XmlReader to separately traverse the tree looking for comments.

    Unfortunately this makes it harder to connect the comments to the deserialized members, but maybe you could use deserialization node event handlers to help with that.

    Update: a little elaboration on using an XmlReader with Deserialize:

    You listed your code as:

    XmlSerializer objSer = new XmlSerializer(typeof(CustomSchema));
    StreamReader srmRdr = new StreamReader("Test.XML");
    objForm = (CustomSchema)objSer.Deserialize(srmRdr);
    

    I don't know anything about .NETCF or WM. (I didn't know anything about XmlSerializer either but I'm just looking at the docs.) However here's what I was trying to describe above.

    I thought you could use an XmlReader for Deserialize() and then re-use it, but apparently it's forward-only and therefore can't be reset to the beginning. So After your deserialization, re-open "Test.XML" with an XmlReader:

    XmlReader xmlRdr = XmlReader.Create("Test.XML");
    

    Then use the parsing code shown here:

        // Parse the file
        while (xmlRdr.Read())
        {
            switch (xmlRdr.NodeType)
            {
                case XmlNodeType.Element:
                    // You may need to capture the last element to provide a context
                    // for any comments you come across... so copy xmlRdr.Name, etc.
                    break;
                case XmlNodeType.Comment:
                    // Do something with xmlRdr.value
    
    0 讨论(0)
  • 2021-01-21 04:43

    It does not say which programming language you are using, but based on this example, which is the exact opposite of what you are trying to do, could you not insert an XmlReader like how an XmlWriter was inserted as accepted answer to that question?

    0 讨论(0)
提交回复
热议问题