Computer >> Máy Tính >  >> Lập trình >> C#

Làm cách nào để chuyển đổi XML sang Json và Json trở lại XML bằng Newtonsoft.json?

Json.NET hỗ trợ chuyển đổi JSON sang XML và ngược lại bằng XmlNodeConverter.

Các phần tử, thuộc tính, văn bản, nhận xét, dữ liệu ký tự, hướng dẫn xử lý, vùng tên và khai báo XML đều được giữ nguyên khi chuyển đổi giữa hai phần này

SerializeXmlNode

JsonConvert có hai phương thức trợ giúp để chuyển đổi giữa JSON và XML. Đầu tiên là SerializeXmlNode (). Phương thức này nhận một XmlNode và tuần tự hóa nó thành văn bản JSON.

DeserializeXmlNode

Phương thức trợ giúp thứ hai trên JsonConvert là DeserializeXmlNode (). Phương thức này nhận văn bản JSON và giải mã hóa nó thành một XmlNode.

Ví dụ 1

static void Main(string[] args) {
   string xml = @"Alanhttps://www.google1.com Admin1";
   XmlDocument doc = new XmlDocument();
   doc.LoadXml(xml);
   string json = JsonConvert.SerializeXmlNode(doc);
   Console.WriteLine(json);
   Console.ReadLine();
}

Đầu ra

{"person":{"@id":"1","name":"Alan","url":"https://www.google1.com","role":"Admin1"}}

Ví dụ 2

static void Main(string[] args) {
   string json = @"{
      '?xml': {
         '@version': '1.0',
         '@standalone': 'no'
      },
      'root': {
         'person': [
            {
            '@id': '1',
            'name': 'Alan',
            'url': 'https://www.google1.com'
            },
            {
            '@id': '2',
            'name': 'Louis',
            'url': 'https://www.yahoo1.com'
            }
         ]
      }
   }";
   XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(json);
   Console.WriteLine(json);
   Console.ReadLine();
}

Đầu ra

'?xml': {
   '@version': '1.0',
   '@standalone': 'no'
},
'root': {
   'person': [
      {
      '@id': '1',
      'name': 'Alan',
      'url': 'https://www.google1.com'
      },
      {
      '@id': '2',
      'name': 'Louis',
      'url': 'https://www.yahoo1.com'
      }
   ]
}