将单个XElement转换为对象

Num*_*m3n 15 .net c# xml xelement linq-to-xml

我有一个XElement看起来像这样:

<row flag="1" sect="" header="" body="" extrainfo="0" />
Run Code Online (Sandbox Code Playgroud)

然后我有一个看起来像这样的课:

public class ProductAttribute
{
    public string Flag { get; set; }
    public string Sect { get; set; }
    public string Header { get; set; }
    public string Body { get; set; }
    public string Extrainfo { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

如何将其XElement转换为ProductAttribute对象?

jbl*_*jbl 14

您必须在类和类成员上放置正确的序列化属性

[Serializable()]
[XmlRoot(ElementName = "row")]
public class ProductAttribute
{
    [XmlAttribute("flag")]
    public string Flag { get; set; }
    [XmlAttribute("sect")]
    public string Sect { get; set; }
    [XmlAttribute("header")]
    public string Header { get; set; }
    [XmlAttribute("body")]
    public string Body { get; set; }
    [XmlAttribute("extrainfo")]
    public string Extrainfo { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

  • 但是您没有解释/显示的是从“XElement”到“ABC”的实际转换。 (2认同)

小智 12

你可以这样做:

1)首先你应该给这个类赋予属性:

[XmlRoot("row")]
public class ProductAttribute
{
    [XmlAttribute("flag")]
    public string Flag { get; set; }
    [XmlAttribute("sect")]
    public string Sect { get; set; }
    [XmlAttribute("header")]
    public string Header { get; set; }
    [XmlAttribute("body")]
    public string Body { get; set; }
    [XmlAttribute("extrainfo")]
    public string Extrainfo { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

2)现在您可以反序列化您的XElement或简单的xml字符串,如下所示:

ProductAttribute productAttribute = new ProductAttribute();
XElement xElement = XElement.Parse(
"<row flag='1' sect='3' header='4444' body='3434' extrainfo='0' />");

//StringReader reader = new StringReader(
//"<row flag='1' sect='3' header='4444' body='3434' extrainfo='0' />");

StringReader reader = new StringReader(xElement.ToString());
XmlSerializer xmlSerializer = new XmlSerializer(typeof(ProductAttribute));
productAttribute = (ProductAttribute)xmlSerializer.Deserialize(reader);
Run Code Online (Sandbox Code Playgroud)

我希望它对你有所帮助.


Alb*_*rto 6

你有没有尝试过:

XElement element = //Your XElement
var serializer = new XmlSerializer(typeof(ProductAttribute));
(ProductAttribute)serializer.Deserialize(element.CreateReader()) 
Run Code Online (Sandbox Code Playgroud)