【问题标题】:Unable to format xml using c#无法使用c#格式化xml
【发布时间】:2013-08-29 08:30:21
【问题描述】:

好的,所以我有 2 节课

public class PRData
{
    public DateTime PRDate { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
}

还有一个是

public class MonthData
{
    public string Months { get; set; }
    public List<PRData> PrList { get; set; }
}

现在我创建了MonthDataPRData 类的实例并填写了一些数据。

        PRData pr = new PRData();
        pr.Title = "hello";
        pr.PRDate = DateTime.Now;
        pr.Description = "Hello world";

        List<PRData> prList =new List<PRData>();
        prList.Add(pr);
        prList.Add(pr);

        MonthData mon = new MonthData();
        mon.Months = "feb";
        mon.PrList = prList;

现在我正在尝试将此对象转换为 xml

string xml = Helper.GetXMLFromObject(mon);

我收到的 xml 是

 <MonthData>
  <Months>feb</Months> 
  <PrList>
    <PRData>
      <PRDate>2012-02-01T00:00:00</PRDate> 
      <Title>hello</Title> 
      <Description>Hello world</Description> 
    </PRData>
    <PRData>
      <PRDate>2012-02-01T00:00:00</PRDate> 
      <Title>hello</Title> 
      <Description>Hello world</Description> 
     </PRData>
  </PrList>
</MonthData>

有什么办法可以去掉PrList标签,让xml看起来像

 <MonthData>
  <Months>feb</Months> 
  <PRData>
    <PRDate>2012-02-01T00:00:00</PRDate> 
    <Title>hello</Title> 
    <Description>Hello world</Description> 
  </PRData>
  <PRData>
    <PRDate>2012-02-01T00:00:00</PRDate> 
    <Title>hello</Title> 
    <Description>Hello world</Description> 
   </PRData>
</MonthData>

我正在使用的函数将对象转换为 xml

 public static string GetXMLFromObject(object o)
    {
        try
        {
            XmlSerializer XmlS = new XmlSerializer(o.GetType());

            StringWriter sw = new StringWriter();
            XmlTextWriter tw = new XmlTextWriter(sw);

            XmlS.Serialize(tw, o);

            return sw.ToString();
        }
        catch (Exception ex)
        {
            throw new DataAccessException("Could Not Serialize object : GetXMLFromObject" + " : " + ex.Message);

        }
    }

注意: 我期待的解决方案是在我的类中进行一些更改,而不是在我上面给出的将对象转换为 xml 的函数中进行一些更改

【问题讨论】:

    标签: c# xml class oop


    【解决方案1】:

    只需将XmlElement 属性应用于PrList 属性:

    using System.Xml.Serialization;
    
    ...
    
    [XmlElement]
    public List<PRData> PrList { get; set; }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-20
      • 2017-06-04
      • 1970-01-01
      • 2021-02-05
      相关资源
      最近更新 更多