locked
Given Xml i want to deserialize xml to XDocument RRS feed

  • Question

  • User-148788041 posted

    Hi,

    How to 

    Given Xml i want to deserialize xml to XDocument

    Ananth

    Sunday, August 19, 2018 8:56 AM

All replies

  • User1120430333 posted

    XDocument.Load(XML)

    You should be able to find plenty of articles by using your friends Bing and Google.

    Sunday, August 19, 2018 11:46 AM
  • User-148788041 posted

    They are forming an empty classs similar to xml tags. i d o not want that to be create as .cs file. The Given xml file must be deserialized as X document.

    Sunday, August 19, 2018 5:30 PM
  • User753101303 posted

    Hi,

    No. XDocument.Load loads the XML document to an object that represents the XML document itself. Isn't it what you are looking for ? The use of "deserialization" is confusing as it is more about loading an XML document as plain .NET data structures matching whatever kind of data needs your app.

    If you need further help, it seems you should give some details so that we better understand which kind of help you are looking for.

    Sunday, August 19, 2018 6:49 PM
  • User-148788041 posted

    Patrice,

    Given an xml as input, i need to deserialize it and convert to Xdocument. How it can be done in a single class file . 

    Monday, August 20, 2018 4:52 PM
  • User753101303 posted

    Answered in the other thread. If this your manager that talked about "deserializing to a XDocument object" it is really confusing. The first thing to clarify would be :

    • is the XML structure known ? If yes then your manager seems wrong and you'll just deserialize that to a structure that matches your need
    • if not you'll have to load that file in a XDocument and may be to "infer" the schema for this XML file so that you can maybe further process this

    Could you clarify if the XML structure of this file is known or not. And if case #2, what you are supposed to do  then from this entirely unknown file ?

    Monday, August 20, 2018 5:52 PM
  • User-148788041 posted

    So please provide and an example how to deserialize a given xml in a single class file.I can convert the deserialized xml to Xdocument.

    Monday, August 20, 2018 10:42 PM
  • User753101303 posted

    I still don't get. it To me it is 2 distinct approaches depending on what you need to do and using both doesn't seems to make really sense.

    Demo1 is what I call "deserialization" ie loading a strongly typed structure (possibly from a previously serialized identical structure).

    Demo2 is just working on an XML Document without knowing in advance anything at all about its content.

    Books.xml is taken from https://docs.microsoft.com/en-us/dotnet/api/system.xml.schema.xmlschemainference?view=netframework-4.7.2#examples

    namespace ConsoleApp1
    {
        // Use http://xmltocsharp.azurewebsites.net/ to generate C# classes from an XML sample file
    
        /* 
       Licensed under the Apache License, Version 2.0
    
       http://www.apache.org/licenses/LICENSE-2.0
       */
        using System;
        using System.Collections.Generic;
        using System.IO;
        using System.Xml.Linq;
        using System.Xml.Serialization;
    
        //namespace Xml2CSharp
        //{
        [XmlRoot(ElementName="author", Namespace="http://www.contoso.com/books")]
    	public class Author {
    		[XmlElement(ElementName="first-name", Namespace="http://www.contoso.com/books")]
    		public string Firstname { get; set; }
    		[XmlElement(ElementName="last-name", Namespace="http://www.contoso.com/books")]
    		public string Lastname { get; set; }
    		[XmlElement(ElementName="name", Namespace="http://www.contoso.com/books")]
    		public string Name { get; set; }
    	}
    
    	[XmlRoot(ElementName="book", Namespace="http://www.contoso.com/books")]
    	public class Book {
    		[XmlElement(ElementName="title", Namespace="http://www.contoso.com/books")]
    		public string Title { get; set; }
    		[XmlElement(ElementName="author", Namespace="http://www.contoso.com/books")]
    		public Author Author { get; set; }
    		[XmlElement(ElementName="price", Namespace="http://www.contoso.com/books")]
    		public string Price { get; set; }
    		[XmlAttribute(AttributeName="genre")]
    		public string Genre { get; set; }
    		[XmlAttribute(AttributeName="publicationdate")]
    		public string Publicationdate { get; set; }
    		[XmlAttribute(AttributeName="ISBN")]
    		public string ISBN { get; set; }
    	}
    
    	[XmlRoot(ElementName="bookstore", Namespace="http://www.contoso.com/books")]
    	public class Bookstore {
    		[XmlElement(ElementName="book", Namespace="http://www.contoso.com/books")]
    		public List<Book> Book { get; set; }
    		[XmlAttribute(AttributeName="xmlns")]
    		public string Xmlns { get; set; }
    	}
    //}
        class Program
        {
            private const  string path = "books.xml";
    
            // Known structure (deserialization)
            static void Demo1()
            {
                Bookstore bookStore;
                var serializer = new XmlSerializer(typeof(Bookstore));
                using (StreamReader reader = new StreamReader(path))
                {
                    bookStore = (Bookstore)serializer.Deserialize(reader);
                }
                foreach(var book in bookStore.Book)
                {
                    Console.WriteLine("{0}, {1}", book.Title, book.Author.Firstname);
                }
            }
            // Unknown structure: XDocument
            static void Demo2()
            {
                var doc = XDocument.Load(path);
                foreach(var elt in doc.Root.Elements())
                {
                    foreach(var att in elt.Attributes())
                    {
                        Console.WriteLine("{0}: {1}", att.Name, att.Value); // do something with the document content whatever it is
                    }
                }
            }
            static void Main(string[] args)
            {
                Demo1();
                Demo2();
            }
        }
    }
    /* The output is :
    The Autobiography of Benjamin Franklin, Benjamin
    The Confidence Man, Herman
    The Gorgias,
    genre: autobiography
    publicationdate: 1981-03-22
    ISBN: 1-861003-11-0
    genre: novel
    publicationdate: 1967-11-17
    ISBN: 0-201-63361-2
    genre: philosophy
    publicationdate: 1991-02-15
    ISBN: 1-861001-57-6
    */

    Tuesday, August 21, 2018 12:47 AM
  • User-148788041 posted

    With out creating Bookstore class  can u deserialize the xml,since each xml has different tags . 

    Bookstore 
    Tuesday, August 21, 2018 1:36 AM
  • User753101303 posted

    Something like https://www.codeproject.com/tips/227139/converting-xml-to-an-dynamic-object-using-expandoo then and you'll have to "inspect" the object to "discover" with name/value pairs are exposed unlike the final "Usage" demo which still assume you know something in advance about which names are exposed ???

    What will you do then with an object about which you start by knowing nothing at all ? If you need further help please EXPLAIN your final goal. I wonder if this requirement is even real or just based on some kind of misunderstanding or at least it would be easier to figure out which path we would try to achieve this - for now unknown - final goal.

    What are you really supposed to do with the XML file from which you start and once it has been "deserialized" ??? Or you expect to be able to write strongly typed code that would work on data about which you know nothing when the code is written ???

    Tuesday, August 21, 2018 2:39 AM
  • User-148788041 posted

    Patrice

    expandoo  works great. But how to convert the Deserialized json to Xdocument . 

    Expando  = JsonConvert.DeserializeObject<Expando>(json);
    how to convert to XDoc
    

    Wednesday, August 22, 2018 7:33 AM
  • User753101303 posted

    Humm... This is NOT the question you asked first !?

    - Given Xml i want to "deserialize" xml to XDocument

    So as shown in the previous sample (and told before multiple times), you can load an XML document to a XDocument object using var doc = XDocument.Load(path);

    And now it seems you were actually asking how to deserialize a json payload to an XDocument ?

    Could you explain once for all what you are trying do to regardless of how you think it could be done ? And fully (ie what you'll do then once you have a XDocument).

    For example one could ask this hoping to then store XML to a db or whatever while your db might support storying (and querying) json data etc...

    Wednesday, August 22, 2018 8:01 AM
  • User-148788041 posted

    My objective is to deserialize xml and convert to XDocument. 

    As per your code i had deserialized xml using Json.Convert. 

    Now i need to convert the json to XDocument.

    Wednesday, August 22, 2018 1:41 PM
  • User753101303 posted

    I'll try a last time.


    Guhananth

    My objective is to deserialize xml and convert to XDocument. 

    You don't "deserialize" XML to a XDocument. You load the XML into a XDocument so that it is easier to work on this XML document. "deserialization" would be taking XML and turning this into a .NET object that has nothing to do with XML (it just happen that this particular instance was created using data persisted using XML). To me you have the answer for that. Case closed.


    Guhananth

    As per your code i had deserialized xml using Json.Convert. 

    I don't see where XML is involved. It seems to just deserialize an object from json which is basically unrelated to all we discussed so far. Case closed.


    Guhananth

    Now i need to convert the json to XDocument.

    So  now you are starting from json, use your code to deserialize an object and would likely to turn this into a XDocument ? In short the steps would be to start form a json file, deserialize this to an object, serialize this object to XML and load this XML to a XDocument (or maybe turn the object direclty to a XDocument if json.net allows that) ?

    But what will you do then with this XDocument. Will you ask to do some operation you don't want to tell about for now ????

    For the last time it would be much easier to help knowing your exact intent rather than asking each time about a small part exactly as it is easier for you if your manager tells what is the final result he want rather than coming each day asking to do something new without letting you know what will be the final result.

    So I'll come up with a sample but if you ask then about some next step for your final - and still unknown to date -  goal, I'll just give up here.

    Wednesday, August 22, 2018 1:50 PM
  • User-148788041 posted

    project requirement is like that. Given an xml,deserialize it and convert to XDocument.

    Wednesday, August 22, 2018 2:19 PM
  • User753101303 posted

    So to me you have the answer since the very first response.

    It seems more a wording issue. Serialization is persisting an object to some format (json, xml) from which you can later rebuild the same object (deserialization). Usually you basically never have to deal directly with the underlying format exactly as you don't have to know anything about the JPG format to save and load an image with MS Paint.

    Before or after the serialization you just have a .NET object which is unrelated to json or XML.

    The purpose of XDocument is to load an XML file in memory so that you can work easily on this XML file. This file is exposed as a whole hierarchy of objects and collections (.NET objects but whose purpose is to expose each particular part of the XML file) so that you can explore and change the content more easily than if you had to work directly on a single string containing a whole XML tag soup.

    Wednesday, August 22, 2018 2:54 PM