How to get a specific object from a Json / XML?

2

I need to get the content within <extract> to use in my application, but I can not. I have tried to create a class with the same objects, I tried to use the regex, but without success.

I have the following XML :

<api batchcomplete="">
    <query>
        <pages>
            <page _idx="21721040" pageid="21721040" ns="0" title="Stack Overflow">
                <extract xml:space="preserve">
                    Stack Overflow is a privately held website, the flagship site of the Stack Exchange Network, created in 2008 by Jeff Atwood and Joel Spolsky. It was created to be a more open alternative to earlier question and answer sites such as Experts-Exchange. The name for the website was chosen by voting in April 2008 by readers of Coding Horror, Atwood's popular programming blog. It features questions and answers on a wide range of topics in computer programming. The website serves as a platform for users to ask and answer questions, and, through membership and active participation, to vote questions and answers up or down and edit questions and answers in a fashion similar to a wiki or Digg. Users of Stack Overflow can earn reputation points and "badges"; for example, a person is awarded 10 reputation points for receiving an "up" vote on an answer given to a question, and can receive badges for their valued contributions, which represents a kind of gamification of the traditional Q&A site or forum. All user-generated content is licensed under a Creative Commons Attribute-ShareAlike license. Closing questions is a main differentiation from Yahoo! Answers and a way to prevent low quality questions. The mechanism was overhauled in 2013; questions edited after being put "on hold" now appear in a review queue. Jeff Atwood stated in 2010 that duplicate questions are not seen as a problem but rather they constitute an advantage if such additional questions drive extra traffic to the site by multiplying relevant keyword hits in search engines. As of April 2014 Stack Overflow has over 4,000,000 registered users, and it exceeded 10,000,000 questions in late August 2015. Based on the type of tags assigned to questions, the top eight most discussed topics on the site are: Java, JavaScript, C#, PHP, Android, jQuery, Python and HTML. Stack Overflow also has a Jobs section to assist developers in finding their next opportunity. For employers, Stack Overflow provides tools to brand their business, advertise their openings on the site, and source candidates from Stack Overflow's database of developers who are open to being contacted.
                </extract>
            </page>
        </pages>
    </query>
</api>

Or the following Json :

{  
   "batchcomplete":"",
   "query":{  
      "pages":{  
         "21721040":{  
            "pageid":21721040,
            "ns":0,
            "title":"Stack Overflow",
            "extract":"Stack Overflow is a privately held website, the flagship site of the Stack Exchange Network, created in 2008 by Jeff Atwood and Joel Spolsky. It was created to be a more open alternative to earlier question and answer sites such as Experts-Exchange. The name for the website was chosen by voting in April 2008 by readers of Coding Horror, Atwood's popular programming blog.\nIt features questions and answers on a wide range of topics in computer programming.\nThe website serves as a platform for users to ask and answer questions, and, through membership and active participation, to vote questions and answers up or down and edit questions and answers in a fashion similar to a wiki or Digg. Users of Stack Overflow can earn reputation points and \"badges\"; for example, a person is awarded 10 reputation points for receiving an \"up\" vote on an answer given to a question, and can receive badges for their valued contributions, which represents a kind of gamification of the traditional Q&A site or forum. All user-generated content is licensed under a Creative Commons Attribute-ShareAlike license.\nClosing questions is a main differentiation from Yahoo! Answers and a way to prevent low quality questions. The mechanism was overhauled in 2013; questions edited after being put \"on hold\" now appear in a review queue. Jeff Atwood stated in 2010 that duplicate questions are not seen as a problem but rather they constitute an advantage if such additional questions drive extra traffic to the site by multiplying relevant keyword hits in search engines.\nAs of April 2014 Stack Overflow has over 4,000,000 registered users, and it exceeded 10,000,000 questions in late August 2015. Based on the type of tags assigned to questions, the top eight most discussed topics on the site are: Java, JavaScript, C#, PHP, Android, jQuery, Python and HTML.\nStack Overflow also has a Jobs section to assist developers in finding their next opportunity. For employers, Stack Overflow provides tools to brand their business, advertise their openings on the site, and source candidates from Stack Overflow's database of developers who are open to being contacted."
         }
      }
   }
}

They are stored in a string.

    
asked by anonymous 07.09.2017 / 00:04

1 answer

1

There are a few ways to work with both and < xml , examples strong>:

For Xml:

[Serializable, XmlRoot("api")]
public class RootObject
{        
    [System.Xml.Serialization.XmlAttribute("batchcomplete")]
    public string BatchComplete { get; set; }
    [System.Xml.Serialization.XmlElement("query")]
    public Query Query { get; set; }
}    
public class Query
{        
    [System.Xml.Serialization.XmlElement("pages")]
    public Pages Pages { get; set; }
}    
public class Pages
{   
    [System.Xml.Serialization.XmlElement("page")]
    public Page Page { get; set; }
}    
public class Page
{        
    [System.Xml.Serialization.XmlAttribute("pageid")]
    public int PageId { get; set; }

    [System.Xml.Serialization.XmlAttribute("ns")]
    public int Ns { get; set; }

    [System.Xml.Serialization.XmlAttribute("title")]
    public string Title { get; set; }

    [System.Xml.Serialization.XmlElement("extract")]
    public string Extract { get; set; }        
}

How to use?

using System.Xml.Serialization;

XmlSerializer s = new XmlSerializer(typeof(RootObject), "");
var result = (RootObject)s.Deserialize(new StreamReader("./f.xml"));
var str = result.Query.Pages.Page.Extract;

For Json:

1) With classes

public class RootObject
{        
    [JsonProperty("batchcomplete")]
    public string BatchComplete { get; set; }
    [JsonProperty("query")]
    public Query Query { get; set; }
}    
public class Query
{        
    [JsonProperty("pages")]
    public Pages Pages { get; set; }
}    
public class Pages
{   
    [JsonProperty("21721040", Required = Required.Always)]
    public Data Datas { get; set; }
}    
public class Data
{        
    [JsonProperty("pageid")]
    public int PageId { get; set; }

    [JsonProperty("ns")]
    public int Ns { get; set; }

    [JsonProperty("title")]
    public string Title { get; set; }

    [JsonProperty("extract")]
    public string Extract { get; set; }        
}

How to use?

string json = System.IO.File.ReadAllText("./j.json");
RootObject result = Newtonsoft.Json.JsonConvert.DeserializeObject<RootObject>(json);

2) Simple:

string json = System.IO.File.ReadAllText("./j.json");
ExpandoObject converter = new ExpandoObject();
dynamic result = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(json, converter);
result = ((ExpandoObject)result.query.pages).FirstOrDefault().Value;
string str = result.extract;

1) With classes

[DataContract()]
public class RootObject
{        
    [DataMember(Name = "batchcomplete")]
    public string BatchComplete { get; set; }
    [DataMember(Name = "query")]
    public Query Query { get; set; }
}
[DataContract()]
public class Query
{        
    [DataMember(Name = "pages")]
    public Pages Pages { get; set; }
}
[DataContract()]
public class Pages
{
    [DataMember(IsRequired = true, Name = "21721040")]
    public Data Data { get; set; }
}

[DataContract()]
public class Data
{        
    [DataMember(Name = "pageid")]
    public int PageId { get; set; }

    [DataMember(Name = "ns")]
    public int Ns { get; set; }

    [DataMember(Name = "title")]
    public string Title { get; set; }

    [DataMember(Name = "extract")]
    public string Extract { get; set; }        
}

How to use?

using System.Runtime.Serialization.Json;

DataContractJsonSerializerSettings settings = 
                new DataContractJsonSerializerSettings();
settings.UseSimpleDictionaryFormat = true;

DataContractJsonSerializer jsonSerializer = 
    new DataContractJsonSerializer(typeof(RootObject));


RootObject rootObj = null;
string json = System.IO.File.ReadAllText("./j.json");
using (MemoryStream strReader = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
    rootObj = (RootObject)jsonSerializer.ReadObject(strReader);
}

var str = rootObj.Query.Pages.Data.Extract;

an indication would use the version for xml , because it has the correct format of keys and values, but, in that case in specific, if json was well formatted would be the best recommendation. p>

07.09.2017 / 04:34