Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

การแปลง XML เป็น JSON และ JSON กลับเป็น XML ด้วย Newtonsoft.Json

Newtonsoft.Json (Json.NET) รองรับการแปลงระหว่าง XML และ JSON ผ่าน XmlNodeConverter และ Helper Methods ใน JsonConvert

เมธอดหลัก

  • JsonConvert.SerializeXmlNode(XmlNode): XML → JSON String
  • JsonConvert.DeserializeXmlNode(string json): JSON → XmlDocument
  • JsonConvert.DeserializeXmlNode(string json, string deserializeRootElementName): ระบุ Root Element

ตัวอย่าง 1: XML → JSON

using Newtonsoft.Json;
using System.Xml;

static void Main()
{
    string xml = @"
  Alan
  https://www.google1.com
  Admin1
";

    XmlDocument doc = new XmlDocument();
    doc.LoadXml(xml);
    
    // Serialize XML to JSON
    string json = JsonConvert.SerializeXmlNode(doc);
    Console.WriteLine(json);
    
    // Pretty Print
    string jsonPretty = JsonConvert.SerializeXmlNode(doc, Formatting.Indented);
    Console.WriteLine(jsonPretty);
}

ผลลัพธ์

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

ตัวอย่าง 2: JSON → XML

static void Main()
{
    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' }
    ]
  }
}";

    // Deserialize JSON to XmlDocument
    XmlDocument doc = JsonConvert.DeserializeXmlNode(json, "root");
    
    Console.WriteLine(doc.OuterXml);
}

ผลลัพธ์ XML



  
    Alan
    https://www.google1.com
  
  
    Louis
    https://www.yahoo1.com
  

รายละเอียด Mapping Rules

XML JSON
Element Property
Attribute Property with @ prefix (e.g. "@id")
Text Content Property Value (String)
Multiple Same-name Elements Array
XML Declaration "?xml" Object
Comments, CDATA, Processing Instructions Preserved (with special properties)

ตัวอย่าง 3: XmlNodeConverter แบบ Manual (ควบคุมได้ละเอียด)

var serializer = new JsonSerializer
{
    Converters = { new XmlNodeConverter() }
};

using (var writer = new StringWriter())
{
    serializer.Serialize(writer, doc);
    string json = writer.ToString();
}

ข้อจำกัด/ข้อควรระวัง

  • JSON ไม่มี Concept ของ Attributes → ใช้ @ Prefix
  • XML Mixed Content (Text + Elements) แปลงได้ยาก
  • Namespaces: ต้อง Handle เองหรือใช้ XmlNamespaceManager
  • Performance: XML ↔ JSON Conversion ค่อนข้างช้า ควรหลีกเลี่ยงใน Hot Path
  • ควรใช้ XmlDocument (Legacy) หรือ XDocument (LINQ to XML) แล้ว Convert

ใน .NET Core/5+

ยังคงใช้ Newtonsoft.Json ได้ (NuGet) หรือเขียน Custom Converter กับ System.Text.Json (ซึ่งไม่มี Built-in XML Support)