开发者

Deserializing the comments in XML file

I am trying to deserialize the following sample XML file.I have created the schema fo开发者_开发百科r this XML file.With the help of schema i am able to deserialize the XML into object.

But my problem is i have a XML comments(ex:<!----Test-->) on my XML file.Deserializer is not reading the comments from the XML to object which i created using schema.

And also i noted there is no entry available in schema for the comment node.

How can i read the comments from XML file to object?


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜