Newtonsoft.Json (Json.NET) hỗ trợ chuyển đổi hai chiều giữa XML và JSON thông qua XmlNodeConverter và các helper method trên JsonConvert.
XML -> JSON: SerializeXmlNode
using Newtonsoft.Json;
using System.Xml;
string xml = @"
Alan
https://www.google.com
Admin
";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
string json = JsonConvert.SerializeXmlNode(doc);
Console.WriteLine(json);
Kết quả JSON
{
"person": {
"@id": "1",
"name": "Alan",
"url": "https://www.google.com",
"role": "Admin"
}
}
- Attribute XML -> property với prefix
@(@id). - Element XML -> property.
- Text content -> value.
JSON -> XML: DeserializeXmlNode
string json = @"{
'?xml': { '@version': '1.0', '@standalone': 'no' },
'root': {
'person': [
{ '@id': '1', 'name': 'Alan', 'url': 'https://www.google.com' },
{ '@id': '2', 'name': 'Louis', 'url': 'https://www.yahoo.com' }
]
}
}";
XmlDocument doc = JsonConvert.DeserializeXmlNode(json);
Console.WriteLine(doc.OuterXml);
Kết quả XML
Alan
https://www.google.com
Louis
https://www.yahoo.com
Lưu ý quan trọng
- JSON phải có root element duy nhất cho DeserializeXmlNode (vd:
root). - XML Declaration: Dùng property đặc biệt
'?xml'trong JSON. - Attributes: Dùng prefix
@(@id,@version). - Namespaces: Hỗ trợ qua
xmlnsattribute. - Mixed content (text + element lẫn nhau): Hỗ trợ hạn chế.
Tuỳ chọn SerializeXmlNode
var settings = new JsonSerializerSettings
{
// Giữ nguyên attribute order (cần Newtonsoft 12+)
// Không có option đặc biệt cho XmlNodeConverter ngoài Formatting
};
string json = JsonConvert.SerializeXmlNode(doc, Formatting.Indented, true);
// true = omitRootObject: bỏ wrapper root element nếu XML có single root
Khi nào dùng chuyển đổi này?
- Tích hợp hệ thống legacy XML với API hiện đại JSON.
- Config file XML -> JSON cho app settings.
- Interop với dịch vụ SOAP/REST.
- Migration dữ liệu.
Tham khảo: System.Text.Json (NET Core 3.0+) không hỗ trợ chuyển đổi XML<->JSON built-in. Cần dùng Newtonsoft.Json hoặc thư viện thứ 3.