Grz*_*nio 6 .net c# xml serialization
我试图反序序化由其中一个内部系统生成的Atom xml.但是,当我尝试:
public static MyType FromXml(string xml)
{
XmlSerializer serializer = new XmlSerializer(typeof(MyType ));
return (MyType) serializer.Deserialize(new StringReader(xml));
}
Run Code Online (Sandbox Code Playgroud)
它会在命名空间的定义上抛出异常:
System.InvalidOperationException: <feed xmlns='http://www.w3.org/2005/Atom'> was not expected.
Run Code Online (Sandbox Code Playgroud)
当我将命名空间添加到XmlSerializer的构造函数时,我的对象是完全空的:
public static MyType FromXml(string xml)
{
XmlSerializer serializer = new XmlSerializer(typeof(MyType ), "http://www.w3.org/2005/Atom");
return (MyType) serializer.Deserialize(new StringReader(xml)); //this will return an empty object
}
Run Code Online (Sandbox Code Playgroud)
任何想法我怎么能让它工作?
Mar*_*ell 10
如果不能看到你的对象模型与xml的关系(即每个的样本),很难对此进行调查; 但是,你应该能够做到这样的事情:
[XmlRoot("feed", Namespace = "http://www.w3.org/2005/Atom")]
public class MyType {...}
Run Code Online (Sandbox Code Playgroud)
作为一个有限的原子示例(与一些样本原子一起使用,我有"手"):
class Program
{
static void Main()
{
string xml = File.ReadAllText("feed.xml");
XmlSerializer serializer = new XmlSerializer(typeof(MyType));
var obj = (MyType)serializer.Deserialize(new StringReader(xml));
}
}
[XmlRoot("feed", Namespace = "http://www.w3.org/2005/Atom")]
public class MyType
{
[XmlElement("id")]
public string Id { get; set; }
[XmlElement("updated")]
public DateTime Updated { get; set; }
[XmlElement("title")]
public string Title { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
您可以通过将此序列化添加到app.config来调试XML序列化
<system.diagnostics>
<switches>
<add name="XmlSerialization.Compilation" value="1" />
</switches>
</system.diagnostics>
Run Code Online (Sandbox Code Playgroud)
在temp-folder中,会生成序列化程序的C#文件,您可以在VS中打开它们进行调试.
还可以查看XmlNamespaceManager(即使是默认名称空间).
| 归档时间: |
|
| 查看次数: |
6130 次 |
| 最近记录: |