将XML字符串转换为通用列表C#

时间:2021-03-01 21:49:57

I have different xml string which should be mapped to different object, Like we convert json string to generic list is there any way to convert xml string to generic list without specifying the tag names. See json deserialize code:

我有不同的xml字符串应该映射到不同的对象,就像我们将json字符串转换为泛型列表有没有办法将xml字符串转换为通用列表而不指定标记名称。请参阅json反序列化代码:

public List<T> DeSerialize<T>(string input)
{
    var serializer = new DataContractJsonSerializer(typeof(List<T>));

    using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(input)))
    {
        return (List<T>)serializer.ReadObject(ms);
    }
}

The above code will deserialize to generic list if the property name of the object and json name are same.

如果对象的属性名称和json名称相同,则上面的代码将反序列化为通用列表。

The code I have now will convert to a specific type not generic list See code below. This should be done without specifying extra property attributes to map xmlnode. Please suggest a generic solution.

我现在的代码将转换为特定类型而非通用列表请参阅下面的代码。这应该在不指定映射xmlnode的额外属性属性的情况下完成。请建议一般的解决方案。

public static T FromXmlString<T>(string xmlString)
{
    var reader = new StringReader(xmlString);
    var serializer = new XmlSerializer(typeof(T));
    var instance = (T)serializer.Deserialize(reader);

    return instance;
}

1 个解决方案

#1


0  

You can follow this way:

你可以这样跟着:

  1. Open Developer Command Prompt You can find it in Start Menu > Programs > Microsoft Visual Studio 2012 > Visual Studio Tools Or if you have Windows 8 can just start typing Developer Command Prompt in Start screen
  2. 打开开发人员命令提示符您可以在“开始”菜单>“程序”>“Microsoft Visual Studio 2012”>“Visual Studio工具”中找到它或者如果您有Windows 8,则可以在“开始”屏幕中键入开发人员命令提示符
  3. Change location to your XML file directory by typing cd /D "C:\path\to\xml"
  4. 通过键入cd / D“C:\ path \ to \ xml”将位置更改为XML文件目录
  5. Create XSD file from your xml file by typing xsd file.xml
  6. 通过键入xsd file.xml从xml文件创建XSD文件
  7. Create C# classes by typing xsd /c file.xsd
  8. 键入xsd / c file.xsd创建C#类

And that's it! You have generated C# classes from xml file in C:\path\to\xml\file.cs

就是这样!您已从C:\ path \到\ xml \ file.cs中的xml文件生成C#类

#1


0  

You can follow this way:

你可以这样跟着:

  1. Open Developer Command Prompt You can find it in Start Menu > Programs > Microsoft Visual Studio 2012 > Visual Studio Tools Or if you have Windows 8 can just start typing Developer Command Prompt in Start screen
  2. 打开开发人员命令提示符您可以在“开始”菜单>“程序”>“Microsoft Visual Studio 2012”>“Visual Studio工具”中找到它或者如果您有Windows 8,则可以在“开始”屏幕中键入开发人员命令提示符
  3. Change location to your XML file directory by typing cd /D "C:\path\to\xml"
  4. 通过键入cd / D“C:\ path \ to \ xml”将位置更改为XML文件目录
  5. Create XSD file from your xml file by typing xsd file.xml
  6. 通过键入xsd file.xml从xml文件创建XSD文件
  7. Create C# classes by typing xsd /c file.xsd
  8. 键入xsd / c file.xsd创建C#类

And that's it! You have generated C# classes from xml file in C:\path\to\xml\file.cs

就是这样!您已从C:\ path \到\ xml \ file.cs中的xml文件生成C#类