Detailed analysis of C # XML, JSON and other formats _c# tutorial

Source: Internet
Author: User

The parsing of XML format data by C #

1, with XmlDocument to resolve

XmlDocument xmldocument = new XmlDocument (); 
Xmldocumentload ("Testxml"); 
 
Create a new node  
XmlElement nn = xmldocumentcreateelement ("image"); 
Nnsetattribute ("ImageUrl", "jpg"); 
 
XmlNode node = xmldocumentselectsinglenode ("Content/section/page/gall/folder");//Navigate to the folder node 
nodeappendchild ( nn);//Attach new node 
 
//Save 
Xmldocumentsave ("Testxml"); 

2. Parse with LINQ to XML

You can iterate through to get the content or attributes of the node you want

XElement root = Xelementload ("Testxml"); 
foreach (XAttribute att in rootattributes ()) 
{ 
  rootadd (new XElement (AttName, (String) att)); 
 

3, with a detailed point of example

For example, to parse the following XML file, convert it to a IList object.

<?xml version= "0" encoding= "utf-8"?> 
<Car> 
 <carcost> 
  <id>20130821133126</ id> 
  <uptime>60</uptime> 
  <downtime>30</downtime> 
  <price>4</ price> 
 </carcost> 
 <carcost> 
  <ID>20130821014316</ID> 
  <uptime> 120</uptime> 
  <downtime>60</downtime> 
  <price>3</price> 
 </ carcost> 
 <carcost> 
  <ID>20130822043127</ID> 
  <uptime>30</uptime> 
  <downtime>0</downtime> 
  <price>5</price> 
 </carcost> 
 < carcost> 
  <ID>20130822043341</ID> 
  <uptime>120 above! </uptime> 
  <downtime>120</downtime> 
  <price>2</price> 
 </carcost > 
</Car> 

Enter the following code in the console application.

Class Program {static void Main (string[] args) {ilist<carcost> resultlist = new List<carcost> () 
 
    ; 
    XmlDocument xmldocument = new XmlDocument (); 
 
    Xmldocumentload ("Testxml"); 
    XmlNodeList XmlNodeList = Xmldocumentselectsinglenode ("car") childnodes; foreach (XmlNode list in XmlNodeList) {carcost carcost = new Carcost (Listselectsinglenode (" 
        ID ") innertext, Listselectsinglenode (" uptime ") innertext, Listselectsinglenode (" Downtime ") innertext, 
      Floatparse (Listselectsinglenode ("price") innertext); 
    Resultlistadd (Carcost); 
    } IEnumerator Enumerator = Resultlistgetenumerator (); 
      while (Enumeratormovenext ()) {Carcost carcost = enumeratorcurrent as carcost; 
    Consolewriteline (Carcostid + "" + Carcostuptime + "" + Carcostdowntime + "" + Carcostprice); }} public class Carcost {public carcost (string ID, string uptime, string downtime, Float price) {thisid = ID; 
    Thisuptime = uptime; 
    Thisdowntime = downtime; 
  Thisprice = Price; 
  public string ID {get; set;} 
  public string UpTime {get; set;} 
  public string Downtime {get; set;} 
Public float price {get; set;} 
 }

Second, C # Analysis of JSON format data

Refer to the Newtonsoftjsondll file for resolution.

For example: There is a JSON string to parse

[{"Taskrolespaces": "", "Taskroles": "", "Proxyuserid": "5d9ad5dc1c5e494db1d1b4d8d79b60a7", "UserID": " 5d9ad5dc1c5e494db1d1b4d8d79b60a7 "," UserName ":" Name "," Usersystemname ":" 2234 "," OperationName ":" Send the contract responsible person "," Operationvalue ":" Consent "," Operationvaluetext ":" "," SignDate ":" 2013-06-19 10:31:26 "," Comment ":" Agree "," Formdatahashcode " : "", "Signaturedivid": ""},{"taskrolespaces": "", "Taskroles": "", "Proxyuserid": "2c96c3943826ea93013826eafe6d0089", "UserID": "2c96c3943826ea93013826eafe6d0089", "UserName": "Name 2", "Usersystemname": "1234", "OperationName": "Send the contract responsible person", "Operationvalue": "Agree", "Operationvaluetext": "", "SignDate": "2013-06-20 09:37:11", "Comment": "Agree", "Formdatahashcode ":" "," Signaturedivid ":" "}]

First, define an entity class:

public class Jobinfo 
{public 
  string taskrolespaces {get; set;} 
  public string Taskroles {get; set;} 
  public string Proxyuserid {get; set;} 
  public string UserID {get; set;} 
  public string UserName {get; set;} 
  public string Usersystemname {get; set;} 
  public string OperationName {get; set;} 
  public string Operationvalue {get; set;} 
  public string Operationvaluetext {get; set;} 
  Public DateTime signdate {get; set;} 
  public string Comment {get; set;} 
  public string Formdatahashcode {get; set;} 
  public string Signaturedivid {get; set;} 
} 

Then enter the following code inside the console main function:

 "> string JSON = @" [{' Taskrolespaces ': ', ' taskroles ': ', ' proxyuserid ': ' 5d9ad5dc1c5e494db1d1b4d8d79b60a7 ', ' UserID ': ' 5d9ad5dc1c5e494db1d1b4d8d79b60a7 ', ' UserName ': ' Name ', ' Usersystemname ' : ' 2234 ', ' operationname ': ' Send the contract owner ', ' Operationvalue ': ' Agree ', ' operationvaluetext ': ', ' signdate ': ' 2013-06-19 10:31:26 ' , ' Comment ': ' Consent ', ' formdatahashcode ': ', ' signaturedivid ': '},{' taskrolespaces ': ', ' taskroles ': ', ' proxyuserid ': ' 2c96c3943826ea93013826eafe6d0089 ', ' UserID ': ' 2c96c3943826ea93013826eafe6d0089 ', ' UserName ': ' Name 2 ', ' Usersystemname ': ' 1234 ', ' operationname ': ' Send the contract owner ', ' Operationvalue ': ' Agree ', ' operationvaluetext ': ', ' signdate ': ' 
  
      2013-06-20 09:37:11 ', ' Comment ': ' Consent ', ' formdatahashcode ': ', ' Signaturedivid ': '} '; 
  
      list<jobinfo> jobinfolist = jsonconvertdeserializeobject<list<jobinfo>> (JSON); foreach (Jobinfo jobinfo in jobinfolist) {consolewriteline ("UserName:" + jobinfousername + "UserID:" + Jo 
      Binfouserid); } 

This will allow you to output the content normally.

I'm sure someone would ask, what if a JSON string with a multi-tiered relationship should be handled? It doesn't matter, the same deal.

Like how to parse this JSON string: [{' Phantom ': TRUE, ' id ': ' 20130717001 ', ' data ': {' MID ': 1019, ' Name ': ' AACCCCC ', ' Des ': ' cc ', ' Disable ': ' Enable ', ' remark ': ' CCCC '}}]?

First or foremost, define the entity classes:

public class Info 
{public 
  string Phantom {get; set;} 
  public string ID {get; set;} 
  Public data data {get; set;} 
} 
 
public class data 
{public 
  int MID {get; set;} 
  public string Name {get; set;} 
  public string Des {get; set;} 
  public string Disable {get; set;} 
  public string Remark {get; set;} 
} 

And then, in the Main method, type:

String json = @ ' [{' phantom ': TRUE, ' id ': ' 20130717001 ', ' data ': {' MID ': 1019, ' Name ': ' AACCCCC ', ' Des ': ' cc ', ' Disable ': ' Enable ' , ' remark ': ' CCCC '}}] '; 
list<info> infolist = jsonconvertdeserializeobject<list<info>> (JSON); 
 
foreach (info info in infolist) 
{ 
  consolewriteline ("ID:" + infodatamid); 

According to our expectations, we should be able to get a 1019 result.

Screenshot as proof:

Another example of JSON parsing comes from a reply from the Rabbit family-two in this blog post.

JSON string 1:{success:true,data:{id:100001,code:\ "Jtl-z38005\", name:\ "Audi Tri-hub \", location:\ "a-202\", qty:100,bins:[{ Code:\ "jtl-z38001\", Name:\ "Audi three Wheels", location:\ "a-001\", qty:100},{code:\ "jtl-z38002\", Name:\ "Audi three Wheels", location:\ " A-002\ ", qty:100}]}}

To define a data structure:

public class Data 
 {public 
   Boolean success {get; set;} 
   Public Data1 data {get; set;} 
 } 
 
 public class Data1 
 {public 
   Int32 ID {get; set;} 
   public string code {get; set;} 
   public string name {get; set;} 
   public string location {get; set;} 
   Public Int32 Qty {get; set;} 
   Public list<data2> Bins {get; set;} 
 } 
 
 public class Data2 
 {public 
   string code {get; set;} 
   public string name {get; set;} 
   public string location {get; set;} 
   Public Int32 Qty {get; set;} 
 } 

Main function:

Class program 
  { 
    static void Main (string[] args) 
    { 
      string json = ' {success:true,data:{id:100001,code:\ "Jtl-z38005\", Name:\ "Audi three Wheels", location:\ "a-202\", qty:100,bins:[{code:\ "jtl-z38001\", Name:\ "Audi three Wheels", location:\ " A-001\ ", qty:100},{code:\" jtl-z38002\ ", Name:\" Audi three wheels \ ", location:\" a-002\ ", qty:100}]}"; 
      Data data = jsonconvertdeserializeobject<data> (JSON); 
 
      foreach (var item in datadatabins) 
      { 
        //output: jtl-z38001, jtl-z38002, other similar 
        consolewriteline (ItemCode); 
      } 
    } 
  } 

JSON string 2:

 {\ "success\": True,\ "data\": {\ "name\": \ "john \", \ "moulds\": {\ "stockimport\": True,\ "stockexport\": true,\ " justifylocation\ ": true,\" justifybin\ ": False,\" binrelease\ ": false}}}

Complete code under the console application:

 namespace ConsoleApplication1 {class Program {static void Main (string[) args) {string json = "{\ Success\": true,\ "data\": {\ "name\": \ "john \", \ "moulds\": {\ "stockimport\": true,\ "Stockexp" 
      Ort\ ": true,\" justifylocation\ ": True,\" justifybin\ ": False,\" binrelease\ ": false}}"; 
      Data data = jsonconvertdeserializeobject<data> (JSON);  Consolewriteline (datadatamouldsbinrelease);//Output False}} public class Data {public Boolean Success { Get Set 
  Data1 data {get; set;} 
    public class Data1 {public string name {get; set;} 
  Public Data2 moulds {get; set;} 
    public class Data2 {public Boolean stockimport {get; set;} 
    Public Boolean Stockexport {get; set;} 
    Public Boolean justifylocation {get; set;} 
    Public Boolean Justifybin {get; set;} 
  Public Boolean binrelease {get; set;} } 
} 

JSON string 3:

{
  "Success": True,
  "data": {
    "id": 100001,
    "bin": "jit-3js-2k",
    "Targetbin": "jit-3js-3k",
    ' Batchs ': [
      ' B20140101 ',
      ' B20140102 '
    ]
  }
}

His main problem is not knowing what to do with Batchs, but it is simply an array.

The complete code is as follows:

Namespace ConsoleApplication1 
{ 
  class program 
  { 
    static void Main (string[] args) 
    { 
      string JSON = "{\ Success\": true,\ "data\": {\ "id\": 100001,\ "bin\": \ "Jit-3js-2k\", \ "targetbin\": \ "Jit-3js-3k\", \ "Batchs\" : [\ "b20140101\", \ "B20140102\"]}} "; 
      Data data = jsonconvertdeserializeobject<data> (JSON); 
 
      foreach (var item in Datadatabatchs) 
      { 
        consolewriteline (item);//output: B20140101, B20140102 
      } 
    } 
  } 
 
  public class Data 
  {public 
    Boolean success {get; set;} 
 
    Public Data1 data {get; set;} 
  } 
 
  public class Data1 
  {public 
    Int32 ID {get; set;} 
 
    public string Bin {get; set;} 
 
    public string Targetbin {get; set;} 
 
    Public string[] Batchs {get; set;}}} 
 

In addition to the entity object practices of the return class above, Jsonnet also provides a jobject class that can take the contents of the node you specify.

Like what:

Namespace ConsoleApplication1 
{ 
  class program 
  { 
    static void Main (string[] args) 
    { 
      string j = " {success:true,data:{bin:{code:\ "jtl-z38001\", Name:\ "Audi three wheels \", location:\ "a-001\", Qty:100}}}; 
      Jobject Jo = (jobject) jsonconvertdeserializeobject (j); 
      Consolewriteline (Jo); 
    } 
 
  public class Data 
  {public 
    Boolean success {get; set;} 
    Public Data1 data {get; set;} 
  } 
 
  public class Data1 
  {public 
    Data2 bin {get; set;} 
  } 
 
  public class Data2 
  {public 
    string code {get; set;} 
    public string name {get; set;} 
    public string location {get; set;} 
    Public Int32 Qty {get; set;}}} 
 

Run directly and return the results as follows:

If the output is modified to read:

 
 

Continue to fetch the bin node.

 
 

Finally, we take the value of the name corresponding to it.

 
 

The value that corresponds to the JSON string is obtained step-by-step.

——————————————————————————————————————————————————

Someone in the group asked a question like, what do I do with the following JSON string?

{
  ' id ': 1,
  ' value ': ' Cate ',
  ' child ': [
    {
      ' id ': 1,
      ' value ': ' Cate ',
      ' child ': [
        
      ]
    } ,
    {
      "id": 1,
      "value": "Cate",
      "child": [
        {
          "id": 2,
          "value": "Cate2",
          "" Child ': [
            {
              ' id ': 3,
              ' value ': ' Cate3 ',
              ' child ': [
                
              ]
  }]}]
}

Through observation we will find that, in fact, the law is better found, that is, including ID, value, child, such as attributes, the child also contains the ID, value, child, such as attributes, can be infinite loop, is a typical tree-shaped structure.

The complete code is as follows:

Namespace ConsoleApplication1 {class Program {static void Main (string[] args) {Data data = new 
      Data (); 
      Dataid = 1; 
      DataValue = "Cate"; 
        Datachild = new List<data> () {new Data () {id=1,value= "Cate", Child=new list<data> () {}},  
            New data () {id=1,value= "Cate", Child=new list<data> () {new data () { id=2, value= "cate2", child = new list<data> () {New Da Ta () {id = 3, value = "Cate3", child = new List<data 
 
      > () {},}},}},}; 
      Serialized as a JSON string string json = Jsonconvertserializeobject (data); 
 
      Consolewriteline (JSON); 
    Deserialized to object Data Jsondata = jsonconvertdeserializeobject<data> (JSON); } public class Data {PublIC int ID {get; set;} 
    public string value {get; set;} 
  Public list<data> Child {get; set;} 
 } 
}

Let's verify the results of the build:

Jobject Jo = (jobject) jsonconvertdeserializeobject (JSON); 

Here's a more complex JSON structure:

 [{"downlist": [], "line": {"Id":-1, "Name": "admin", "icCa
        Rd ": 1"}, "Uplist": [{"Endtime": "18:10", "StartTime": "06:40", "sId": 385,
        "Stype": "Endtime"}, {"18:10": "StartTime": "06:40", "sId": 1036, "Stype": "Downlist"}]}, {"Iccar": [], "line": {"Id":-1, "Name": "admin", "
        D ":" 1 "}," Uplist ": [{" Endtime ":" 18:10 "," StartTime ":" 06:40 "," sId ": 385, "Stype": "Endtime"}, {"18:10": "StartTime": "06:40", "sId": 1036, " Stype ': ' The ' (}]}] 
Namespace ConsoleApplication1 {class Program {static void Main (string[] args) {string Jsonstri ng = "[{\ downlist\": [],\ "line\": {\ "id\": -1,\ "name\": \ "admin\", \ "iccard\": \ "1\"},\ "uplist\": [{\ "endtime\": \ "] 18:10\ ", \" starttime\ ": \" 06:40\ "," sid\ ": 385,\" stype\ ":" 38\ "},{\" endtime\ ": \" 18:10\ ", \" starttime\ ": \" 06:40\ ", \ "sid\": 1036,\ "stype\": \ "38\"}]},{\ "downlist\": [],\ "line\": {\ "id\": -1,\ "name\": \ "admin\", \ "iccard\": \ "1\"},\ " Uplist\ ": [{\ endtime\]: \" 18:10\ "," starttime\ ": \" 06:40\ "," sid\ ": 385,\" stype\ ": \" 38\ "},{\" endtime\ ": \" 18:10\ ", 
      \ "starttime\": \ "06:40\", \ "sid\": 1036,\ "stype\": \ "38\"}]} "; 
 
      data[] datas = jsonconvertdeserializeobject<data[]> (jsonstring); 
        foreach (data data in datas) {downlist[] downlist = datadownlist; 
        Line line = Dataline; 
 
        uplist[] uplists = datauplist; 
        Output Consolewriteline (Stringjoin (",", LineId, Linename, Lineiccard)); foreach (UplisT uplist in uplists) {Consolewriteline (Stringjoin (",", Uplistendtime, Upliststarttime, Uplistsid, UpL 
        Iststype)); 
      } consolewriteline ("-----------------------------------------------"); 
    }} public class Data {public downlist[] downlist {get; set;} 
    Public line line {get; set;} 
  Public uplist[] Uplist {get; set;} 
    public class Downlist {} public class line {public int Id {get; set;} 
    public string Name {get; set;} 
  public string Iccard {get; set;} 
 
    public class Uplist {public string Endtime {get; set;} 
 
    public string StartTime {get; set;} 
 
    public int SId {get; set;} 
  public string Stype {get; set;} 

 } 
}

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.