2

Preciso pegar o conteúdo dentro de <extract> para utilizar em minha aplicação, mas não estou conseguindo. Já tentei criar uma classe com os mesmos objetos, já tentei utilizar o regex, mas sem sucesso.

Tenho o seguinte 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>

Ou o seguinte 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."
         }
      }
   }
}

Eles estão guardados em uma string.

1 Resposta 1

1

Existem algumas formas de trabalhar tanto com e com , exemplos:

Para 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; }        
}

Como usar?

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;

Para Json:

1) Com 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; }        
}

Como usar?

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

2) Simples:

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) Com 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; }        
}

Como usar?

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;

Observação: Essas formas, lhe dão oportunidade de trabalhar com todas as informações contidas tanto no xml quanto no json, se for para dar uma indicação utilize a versão para xml, porque, tem o formato correto de chaves e valores, mas, isso é nesse caso em especifico, se o json estivesse bem formatado seria essa a melhor recomendação.

Referencias

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .