给定以下XML:
<webParts>
<webPart xmlns="http://schemas.microsoft.com/WebPart/v3">
<title>Title One</title>
</webPart>
<webPart xmlns="http://schemas.microsoft.com/WebPart/v3">
<title>Title Two</title>
</webPart>
</webParts>
以及以下c#:
[XmlRoot("webParts")]
public class webParts : List<webPart>
{
static public webParts FromXml(string path)
{
webParts returnValue = null;
var serializer = new XmlSerializer(typeof(webParts));
using (var stream = File.OpenRead(path))
{
returnValue = (webParts)serializer.Deserialize(stream);
}
return returnValue;
}
}
public class webPart
{
public string title { get; set; }
}
我正在尝试反序列化XML。我无法控制XML,可以更改c#。如果我在webPart元素中删除了名称空间,则可以在反序列化过程中执行此操作,它可以正常工作。但是,似乎有点糊涂。我觉得应该将XML属性添加到类中,但找不到正确的命名空间标签组合。上面的代码反序列化了webPart,但是计数为0,没有一个webPart元素被反序列化。为了使这项工作对C#应该做什么?谢谢!
在大多数情况下,使用VS从XML构建类是一项非常简单的任务。
您问题中的XML将转换为该结构
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute( "code" )]
[System.Xml.Serialization.XmlTypeAttribute( AnonymousType = true )]
[System.Xml.Serialization.XmlRootAttribute( Namespace = "", IsNullable = false )]
public partial class webParts
{
private webPart[ ] webPartField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute( "webPart", Namespace = "http://schemas.microsoft.com/WebPart/v3" )]
public webPart[ ] webPart
{
get
{
return this.webPartField;
}
set
{
this.webPartField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute( "code" )]
[System.Xml.Serialization.XmlTypeAttribute( AnonymousType = true, Namespace = "http://schemas.microsoft.com/WebPart/v3" )]
[System.Xml.Serialization.XmlRootAttribute( Namespace = "http://schemas.microsoft.com/WebPart/v3", IsNullable = false )]
public partial class webPart
{
private string titleField;
/// <remarks/>
public string title
{
get
{
return this.titleField;
}
set
{
this.titleField = value;
}
}
}
那可以用来转换你的xml
public partial class webParts
{
static public webParts FromXml(string path)
{
webParts returnValue = null;
var serializer = new XmlSerializer(typeof(webParts));
using (var stream = File.OpenRead(path))
{
returnValue = (webParts)serializer.Deserialize(stream);
}
return returnValue;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句