List<T> to XML 字符串扩展方法
List<T> to XML string Extension Method
如何创建扩展方法以将我的 T 列表转换为 XML 字符串。
我的 T 对象的 属性 变成 xml 标签,属性 的值变成 xml 标签内的值。我的 T 对象具有简单的字符串属性,即没有集合或二维对象。也就是说,所有属性都是字符串、整数等,即一维的..没有 lists/arrays 作为 属性。
如果你想转换例如这种列表:
List<int> Branches = new List<int>();
Branches.Add(1);
Branches.Add(2);
Branches.Add(3);
进入这个XML:
<Branches>
<branch id="1" />
<branch id="2" />
<branch id="3" />
</Branches>
您可以使用 LINQ 尝试此操作:
List<int> Branches = new List<int>();
Branches.Add(1);
Branches.Add(2);
Branches.Add(3);
XElement xmlElements = new XElement("Branches", Branches.Select(i => new XElement("branch", new XAttribute("id", i))));
System.Console.Write(xmlElements);
System.Console.Read();
输出:
<Branches>
<branch id="1" />
<branch id="2" />
<branch id="3" />
</Branches>
您需要包含 using System.Xml.Linq;
命名空间。
编辑:要制作文件,您可以使用此方法
public string ToXML<T>(T obj)
{
using (StringWriter stringWriter = new StringWriter(new StringBuilder()))
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
xmlSerializer.Serialize(stringWriter, obj);
return stringWriter.ToString();
}
}
创建扩展方法与创建常规方法没有太大区别。如果使用关键字 "this" 指定第一个参数(方法将扩展的对象),则只需将方法设为静态即可。剩下的只是计划反思。
public static string GetXML<T>(this List<T> src)
{
// First, we have to determine the "Type" of the generic parameter.
Type srcType = src.GetType();
Type[] srcTypeGenArgs = srcType.GetGenericArguments();
if (srcTypeGenArgs.Length != 1)
throw new Exception("Only designed to work on classes with a single generic param.");
Type genType = srcTypeGenArgs[0];
// Get the properties for the generic Type "T".
System.Reflection.PropertyInfo[] typeProps = genType.GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.GetProperty);
// Now, we loop through each item in the list and extract the property values.
StringBuilder sb = new StringBuilder();
sb.AppendLine("<root>");
for (int i = 0; i < src.Count; i++)
{
T listItem = src[i];
for (int t = 0; t < typeProps.Length; t++)
{
object propVal = typeProps[t].GetValue(listItem, null); // Always pass "null" for the index param, if we're not dealing with some indexed type (like an array).
string propValStr = (propVal != null ? propVal.ToString() : string.Empty);
sb.AppendLine(string.Format("<{0}>{1}</{0}>", typeProps[t].Name, propValStr));
}
}
sb.AppendLine("</root>");
return sb.ToString();
}
您所说的大致翻译为 "serialization",并且像大多数一般问题一样,这个问题已解决。该框架当然为您提供了一些用于 Xml 序列化的工具。
给定一个 class:
public class TestClass
{
public string Prop1 {get;set;}
public string Prop2 {get;set; }
}
还有一个扩展方法:
public static class SerializationExtensions
{
public static string ToXml<T>(this List<T> list)
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(List<T>));
StringWriter stringWriter = new StringWriter();
XmlTextWriter xmlWriter = new XmlTextWriter(stringWriter);
xmlWriter.Formatting = Formatting.Indented;
xmlSerializer.Serialize(xmlWriter, list);
return stringWriter.ToString();
}
}
一个简单的演示生成 xml
<?xml version="1.0" encoding="utf-16"?>
<ArrayOfTestClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<TestClass>
<Prop1>val1</Prop1>
<Prop2>val2</Prop2>
</TestClass>
<TestClass>
<Prop1>val1</Prop1>
<Prop2>val2</Prop2>
</TestClass>
<TestClass>
<Prop1>val1</Prop1>
<Prop2>val2</Prop2>
</TestClass>
</ArrayOfTestClass>
序列化为文件而不是字符串会很简单,但为了演示用法,输出为字符串更容易。
如何创建扩展方法以将我的 T 列表转换为 XML 字符串。 我的 T 对象的 属性 变成 xml 标签,属性 的值变成 xml 标签内的值。我的 T 对象具有简单的字符串属性,即没有集合或二维对象。也就是说,所有属性都是字符串、整数等,即一维的..没有 lists/arrays 作为 属性。
如果你想转换例如这种列表:
List<int> Branches = new List<int>();
Branches.Add(1);
Branches.Add(2);
Branches.Add(3);
进入这个XML:
<Branches>
<branch id="1" />
<branch id="2" />
<branch id="3" />
</Branches>
您可以使用 LINQ 尝试此操作:
List<int> Branches = new List<int>();
Branches.Add(1);
Branches.Add(2);
Branches.Add(3);
XElement xmlElements = new XElement("Branches", Branches.Select(i => new XElement("branch", new XAttribute("id", i))));
System.Console.Write(xmlElements);
System.Console.Read();
输出:
<Branches>
<branch id="1" />
<branch id="2" />
<branch id="3" />
</Branches>
您需要包含 using System.Xml.Linq;
命名空间。
编辑:要制作文件,您可以使用此方法
public string ToXML<T>(T obj)
{
using (StringWriter stringWriter = new StringWriter(new StringBuilder()))
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
xmlSerializer.Serialize(stringWriter, obj);
return stringWriter.ToString();
}
}
创建扩展方法与创建常规方法没有太大区别。如果使用关键字 "this" 指定第一个参数(方法将扩展的对象),则只需将方法设为静态即可。剩下的只是计划反思。
public static string GetXML<T>(this List<T> src)
{
// First, we have to determine the "Type" of the generic parameter.
Type srcType = src.GetType();
Type[] srcTypeGenArgs = srcType.GetGenericArguments();
if (srcTypeGenArgs.Length != 1)
throw new Exception("Only designed to work on classes with a single generic param.");
Type genType = srcTypeGenArgs[0];
// Get the properties for the generic Type "T".
System.Reflection.PropertyInfo[] typeProps = genType.GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.GetProperty);
// Now, we loop through each item in the list and extract the property values.
StringBuilder sb = new StringBuilder();
sb.AppendLine("<root>");
for (int i = 0; i < src.Count; i++)
{
T listItem = src[i];
for (int t = 0; t < typeProps.Length; t++)
{
object propVal = typeProps[t].GetValue(listItem, null); // Always pass "null" for the index param, if we're not dealing with some indexed type (like an array).
string propValStr = (propVal != null ? propVal.ToString() : string.Empty);
sb.AppendLine(string.Format("<{0}>{1}</{0}>", typeProps[t].Name, propValStr));
}
}
sb.AppendLine("</root>");
return sb.ToString();
}
您所说的大致翻译为 "serialization",并且像大多数一般问题一样,这个问题已解决。该框架当然为您提供了一些用于 Xml 序列化的工具。
给定一个 class:
public class TestClass
{
public string Prop1 {get;set;}
public string Prop2 {get;set; }
}
还有一个扩展方法:
public static class SerializationExtensions
{
public static string ToXml<T>(this List<T> list)
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(List<T>));
StringWriter stringWriter = new StringWriter();
XmlTextWriter xmlWriter = new XmlTextWriter(stringWriter);
xmlWriter.Formatting = Formatting.Indented;
xmlSerializer.Serialize(xmlWriter, list);
return stringWriter.ToString();
}
}
一个简单的演示生成 xml
<?xml version="1.0" encoding="utf-16"?>
<ArrayOfTestClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<TestClass>
<Prop1>val1</Prop1>
<Prop2>val2</Prop2>
</TestClass>
<TestClass>
<Prop1>val1</Prop1>
<Prop2>val2</Prop2>
</TestClass>
<TestClass>
<Prop1>val1</Prop1>
<Prop2>val2</Prop2>
</TestClass>
</ArrayOfTestClass>
序列化为文件而不是字符串会很简单,但为了演示用法,输出为字符串更容易。