Home Backend Development C#.Net Tutorial How to use XML and JSON data formats for data storage and transmission in C# and solutions

How to use XML and JSON data formats for data storage and transmission in C# and solutions

Oct 09, 2023 pm 04:58 PM
data analysis xml storage json storage

How to use XML and JSON data formats for data storage and transmission in C# and solutions

How to use XML and JSON data formats for data storage and transmission in C# and solutions

XML and JSON are currently widely used in data exchange and storage standard format. In C#, we can use built-in libraries and tools to process and manipulate XML and JSON data. This article will introduce in detail how to use XML and JSON for data storage and transmission in C#, and provide specific code examples.

1. XML data format

XML (Extensible Markup Language) is a standard format for storing and transmitting data. In C#, we can use the classes provided by the System.Xml namespace to read and write XML data.

1.1 Reading XML data

First, we need to create an XmlDocument object and load XML data into the object. The following is a sample code that reads an XML file and prints the data to the console:

using System;
using System.Xml;

public class Program
{
    public static void Main()
    {
        // 创建XmlDocument对象
        XmlDocument xmlDoc = new XmlDocument();
        
        // 加载XML文件
        xmlDoc.Load("data.xml");
        
        // 获取根节点
        XmlNode rootNode = xmlDoc.SelectSingleNode("root");
        
        // 遍历子节点
        foreach(XmlNode node in rootNode.ChildNodes)
        {
            Console.WriteLine("Name: " + node.Name);
            Console.WriteLine("Value: " + node.InnerText);
        }
    }
}
Copy after login

In the above code, we load the XML file using the XmlDocument.Load() method and select using the SelectSingleNode() method root node. We can then get the node name and node value by iterating over the child nodes.

1.2 Writing of XML data

If we want to write data to an XML file, we can use the methods provided by the XmlDocument object to create nodes and set the properties and values ​​of the nodes. The following is a sample code that writes data to an XML file:

using System;
using System.Xml;

public class Program
{
    public static void Main()
    {
        // 创建XmlDocument对象
        XmlDocument xmlDoc = new XmlDocument();
        
        // 创建根节点
        XmlNode rootNode = xmlDoc.CreateElement("root");
        
        // 创建子节点
        XmlNode childNode1 = xmlDoc.CreateElement("name");
        childNode1.InnerText = "John";
        
        XmlNode childNode2 = xmlDoc.CreateElement("age");
        childNode2.InnerText = "25";
        
        // 将子节点添加到根节点
        rootNode.AppendChild(childNode1);
        rootNode.AppendChild(childNode2);
        
        // 将根节点添加到XmlDocument对象
        xmlDoc.AppendChild(rootNode);
        
        // 保存XmlDocument对象到文件
        xmlDoc.Save("data.xml");
    }
}
Copy after login

In the above code, we create a node using the CreateElement() method provided by the XmlDocument object and set the value of the node using the InnerText property. We then add child nodes to the root node and add the root node to the XmlDocument object via the AppendChild() method. Finally, we can save the XmlDocument object to the XML file using the Save() method.

2. JSON data format

JSON (JavaScript Object Notation) is a lightweight data exchange format. In C#, we can use Newtonsoft.Json library to serialize and deserialize JSON data.

2.1 Serialization of JSON data

First, we need to serialize the C# object into JSON data. The following is a sample code that serializes a C# object into JSON data and prints it to the console:

using System;
using Newtonsoft.Json;

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

public class Program
{
    public static void Main()
    {
        // 创建Person对象
        Person person = new Person
        {
            Name = "John",
            Age = 25
        };
        
        // 序列化Person对象为JSON数据
        string json = JsonConvert.SerializeObject(person);
        
        // 打印JSON数据
        Console.WriteLine(json);
    }
}
Copy after login

In the above code, we use the JsonConvert.SerializeObject() method to serialize the Person object into JSON data, And use the Console.WriteLine() method to print the JSON data.

2.2 Deserialization of JSON data

If we have a string containing JSON data, we can deserialize it into a C# object. The following is a sample code that deserializes JSON data into a C# object and prints it to the console:

using System;
using Newtonsoft.Json;

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

public class Program
{
    public static void Main()
    {
        // JSON数据
        string json = "{"Name":"John","Age":25}";
        
        // 反序列化JSON数据为Person对象
        Person person = JsonConvert.DeserializeObject<Person>(json);
        
        // 打印Person对象的属性
        Console.WriteLine("Name: " + person.Name);
        Console.WriteLine("Age: " + person.Age);
    }
}
Copy after login

In the above code, we use the JsonConvert.DeserializeObject() method to deserialize the JSON data into a Person object, and use the Console.WriteLine() method to print the properties of the Person object.

To sum up, by using the built-in libraries and tools in C#, we can easily process and manipulate XML and JSON data. The above is a detailed introduction to using XML and JSON for data storage and transmission in C#, and provides specific code examples.

The above is the detailed content of How to use XML and JSON data formats for data storage and transmission in C# and solutions. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Article Tags

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to interact with database and store in XML format in PHP How to interact with database and store in XML format in PHP Jul 30, 2023 pm 05:21 PM

How to interact with database and store in XML format in PHP

How to use XML and JSON data formats for data storage and transmission in C# and solutions How to use XML and JSON data formats for data storage and transmission in C# and solutions Oct 09, 2023 pm 04:58 PM

How to use XML and JSON data formats for data storage and transmission in C# and solutions

Data analysis and processing skills that must be mastered in Java crawlers Data analysis and processing skills that must be mastered in Java crawlers Dec 26, 2023 pm 05:45 PM

Data analysis and processing skills that must be mastered in Java crawlers

Ways to extract data from XML and JSON files on the web Ways to extract data from XML and JSON files on the web Jun 13, 2023 am 09:05 AM

Ways to extract data from XML and JSON files on the web

Java development data parsing performance optimization method Java development data parsing performance optimization method Jun 29, 2023 pm 10:19 PM

Java development data parsing performance optimization method

Application analysis of PHP data cache in high concurrency scenarios Application analysis of PHP data cache in high concurrency scenarios Aug 10, 2023 pm 11:21 PM

Application analysis of PHP data cache in high concurrency scenarios

Golang data conversion skills and examples sharing Golang data conversion skills and examples sharing Dec 23, 2023 am 10:01 AM

Golang data conversion skills and examples sharing

How to manipulate binary files in Golang? How to manipulate binary files in Golang? Mar 21, 2024 am 10:18 AM

How to manipulate binary files in Golang?

See all articles