先贴一段xml与实体类互转的代码
public class XmlTools
{
/// <summary>
/// xml转实体类
/// </summary>
/// <typeparam name="T">实体类模板</typeparam>
/// <param name="str">xml字符串</param>
/// <returns>实体T</returns>
public static T XmlToEntity<T>(string str) where T : class
{
try
{
using (StringReader sr = new StringReader(str))
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
return serializer.Deserialize(sr) as T;
}
}
catch
{
return null;
}
}
/// <summary>
/// 实体类转Xml
/// </summary>
/// <typeparam name="T">实体类模板</typeparam>
/// <param name="t">实体类</param>
/// <returns>xml字符串</returns>
public static string EntityToXml<T>(T t)
{
using (StringWriter sw = new StringWriter(new StringBuilder()))
{
try
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
serializer.Serialize(sw, t);
sw.Close();
//生成xml文件到桌面
//XmlDocument xmlDoc = new XmlDocument();
//xmlDoc.LoadXml(sw.ToString());
//xmlDoc.Save("C:\\Users\\Administrator\\Desktop\\myXml.xml");
return sw.ToString();
}
catch
{
return null;
}
}
}
}
xml转实体类失败的原因看了很多文章都没说到点子上,在xml确认格式没问题的情况下其实失败原因主要在于两点:
1.有些xml的对应实体类字段的参数被存到了节点属性而非子节点, 而serializer.Deserialize(sr) 这个方法只能将子节点和字段对应转换。通过如下方法进行转换
/// <summary>
/// xml属性转换成子节点
/// </summary>
/// <param name="nodeList">根节点</param>
private static void AttributeToNode(XmlNodeList nodeList)
{
for (int i = 0; i < nodeList.Count; i++)
{
if (nodeList[i].Attributes != null && nodeList[i].Attributes.Count != 0)
{
for (int j = 0; j < nodeList[i].Attributes.Count; j++)
{
XmlNode node = document.CreateNode("element", nodeList[i].Attributes[j].Name, "");
node.InnerText = nodeList[i].Attributes[j].Value;
nodeList[i].AppendChild(node);
}
nodeList[i].Attributes.RemoveAll();
}
if (nodeList[i].ChildNodes != null && nodeList[i].ChildNodes.Count != 0)
{
AttributeToNode(nodeList[i].ChildNodes);
}
}
}
2.转换失败的原因在于根节点缺少如下命名空间
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"
至于怎么加进入,我用的是笨办法
string xml=xmlStr.Replace("<根节点名称>", "<根节点名称 xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">");
3.经常性的有些人发现,当把json或者xml文件作为配置文件保存在本地,一旦进行了参数修改保存,再读取该文件字符串进行相应的json或者xml转换就会报错,错误原因很可能是因为读取的字符串首字符为空字节,删除掉它再转换即可。