对象类
//XML命名空间,可用于与反序列化方法中指定当前节点的前缀,需要注意的是,此方法指定命名空间所修改的前缀对当前节点包含的所有子节点生效,对当前节点本身不生效,当前节点的前缀继承父节点
[XmlRoot(Namespace = "http://这是一个AAA的网址/")]
public class AAA
{
public BBB bbb { get; set; }
}
[XmlRoot(Namespace = "http://这是一个BBB的网址/")]
public class BBB
{
public CCC ccc { get; set; }
}
public class CCC
{
public string str { get; set; }
}
XML反序列化方法
/// <summary>
/// 将一个对象序列化为XML字符串
/// </summary>
/// <param name="o">要序列化的对象</param>
/// <param name="encoding">编码方式</param>
/// <returns>序列化产生的XML字符串</returns>
public static string XmlSerialize(object o, Encoding encoding)
{
if (o == null)
throw new ArgumentNullException("o");
if (encoding == null)
throw new ArgumentNullException("encoding");
string xml = "";
try
{
using (MemoryStream stream = new MemoryStream())
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = encoding;
//OmitXmlDeclaration表示不生成声明头,默认是false,OmitXmlDeclaration为true,会去掉<?xml version="1.0" encoding="UTF-8"?>
//settings.OmitXmlDeclaration = true;
XmlWriter writer = XmlWriter.Create(stream, settings);
#region 指定命名空间前缀的方法
//强制指定命名空间,覆盖默认的命名空间,可以添加多个,如果要在xml节点上添加指定的前缀,可以在跟节点的类上面添加[XmlRoot(Namespace = "http://www.w3.org/2001/XMLSchema-instance", IsNullable = false)],Namespace指定哪个值,xml节点添加的前缀就是哪个命名空间(这里会添加ceb)
XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
namespaces.Add("AAAA", "http://这是一个AAA的网址/");
namespaces.Add("BBBB", "http://这是一个BBB的网址/");
//namespaces.Add(参数1, 参数2);
//解读:"参数1"为要使用的前缀,对应类中使用"参数2"的命名空间的节点
#endregion
XmlSerializer serializer = new XmlSerializer(o.GetType());
serializer.Serialize(writer, o, namespaces);
writer.Close();
stream.Position = 0;
using (StreamReader reader = new StreamReader(stream, encoding))
{
xml = reader.ReadToEnd();
}
}
}
catch (Exception ex)
{
}
return xml;
}
使用
AAA a = new AAA();
a.bbb = new BBB();
a.bbb.ccc = new CCC();
a.bbb.ccc.str = "指定前缀示例";
string s = XMLtool.XmlSerialize(a, Encoding.UTF8);
结果
<?xml version="1.0" encoding="utf-8"?>
<AAAA:AAA xmlns:AAAA="http://这是一个AAA的网址/" xmlns:BBBB="http://这是一个BBB的网址/">
<AAAA:bbb>
<BBBB:ccc>
<BBBB:str>指定前缀示例</BBBB:str>
</BBBB:ccc>
</AAAA:bbb>
</AAAA:AAA>
感谢!参考来源:https://www.cnblogs.com/zfylzl/p/5653432.html