以下示例假设您有一个名为 Form1 (Form1.cs) 的表单。
尝试以下方法:
安装 Newtonsoft NuGet 包
- 在菜单上,查看
- 选择解决方案资源管理器
- 在解决方案资源管理器中,右键单击
- 选择管理 NuGet 包...
- 点击浏览
- 搜索:Newtonsoft.Json
- 点击Newtonsoft.Json
- 点击安装
创建一个名为 Foo 的类
Foo.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace NewtonsoftEmptyXmlElement
{
[XmlRoot(ElementName = "Foo")]
public class Foo
{
[XmlElementAttribute(ElementName = "Identifier")]
public string Identifier { get; set; }
[XmlArrayAttribute("Data")]
public List<string> Data { get; set; } = new List<string>();
}
}
Form1.cs
添加以下 using 语句:
using Newtonsoft.Json;
using System.Xml;
using System.Diagnostics;
using System.IO;
using System.Xml.Serialization;
GenerateXml(将 XML 作为字符串返回)
public static string GenerateXml<T>(object obj, System.Text.Encoding encoding)
{
string xml = string.Empty;
using (MemoryStream ms = new MemoryStream())
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
//eliminate "xsd" and "xsi" namespaces
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
//indent Xml and eliminate Xml declaration
XmlWriterSettings writerSettings = new XmlWriterSettings();
writerSettings.OmitXmlDeclaration = true;
writerSettings.Encoding = encoding;
writerSettings.Indent = true;
//create instance of XmlWriter
XmlWriter writer = XmlWriter.Create(ms, writerSettings);
serializer.Serialize(writer, (T)obj, ns);
xml = encoding.GetString(ms.ToArray());
}
return xml;
}
WriteXML(将 XML 写入文件)
public static void WriteXml<T>(object obj, string filename, System.Text.Encoding encoding)
{
string xml = string.Empty;
try
{
using (StreamWriter fs = new StreamWriter(filename))
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
//eliminate "xsd" and "xsi" namespaces
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
//indent Xml and eliminate Xml declaration
XmlWriterSettings writerSettings = new XmlWriterSettings();
writerSettings.OmitXmlDeclaration = true;
writerSettings.Encoding = encoding;
writerSettings.Indent = true;
//create instance of XmlWriter
XmlWriter writer = XmlWriter.Create(fs, writerSettings);
serializer.Serialize(writer, (T)obj, ns);
}
}
catch(Exception ex)
{
System.Diagnostics.Debug.WriteLine("Error: - " + ex.Message);
}
}
测试
private void Test()
{
string json = @"
{
""Identifier"": ""MyID"",
""Data"": []
}";
//System.Diagnostics.Debug.WriteLine(json);
Foo foo2 = Newtonsoft.Json.JsonConvert.DeserializeObject<Foo>(json, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Include });
//Option 1 - get XML
string xmlDoc = GenerateXml<Foo>(foo2, System.Text.Encoding.UTF8);
System.Diagnostics.Debug.WriteLine("\n\n" + xmlDoc);
//Option 2 - write XML to file
WriteXml<Foo>(foo2, @"C:\Temp\foo.xml", System.Text.Encoding.UTF8);
}
使用方法:
Test();
输出:
<Foo>
<Identifier>MyID</Identifier>
<Data />
</Foo>