如何使用c#构建对象图并将它们转换为xml文件

时间:2017-10-25 06:45:34

标签: c# xml

附加的输出xml文件......我还需要创建一个合适的类,输出文件应如下所示:

<CMS>
  <Device TB="CM_HOST" properties="{'Name':'Host', 'Type' : 'TR' }" >
      <PortA Connected_BY= "MiniBot">
        <Device TB="TR" ParentConnectedToPort ='PortB' properties="{'Pins': {'MiniBot_minus_pin': 2, 'MiniBot_pluse_pin': 3}, 'Type': 'TR' , 'FTDI_Port':0 ,'Name':'SV_Board','Cable': '20G Passive' }" >   
          <PortB Connected_BY= "MiniBot">
            <Device TB="AR" ParentConnectedToPort ='PortB' properties="{'Pins': {'MiniBot_minus_pin': 0, 'MiniBot_pluse_pin': 1},'Type': 'AR' , 'FTDI_Port':0 ,'Name':'StarTechDoc','Cable': '20G Passive' }">
                <PortA Connected_BY= "Directly">
                    <Device TB="None" properties="{'Type': 'None' , 'FTDI_Port':0 ,'Name':'samsung-USB3','Cable': '20G Passive'}" ></Device>
                </PortA>
                <PortB Connected_BY= "ParentConnected"></PortB>
                <PortE><Device TB="None" properties="{'Type': 'None' , 'FTDI_Port':0 ,'Name':'samsung-USB3','Cable': '20G Passive'}" ></Device></PortE>
            </Device>
          </PortB>
            <PortA Connected_BY= "ParentConnected"></PortA>
          <PortE Connected_BY= "None"></PortE>
        </Device>
      </PortA>
      <PortB Connected_BY= "None"></PortB>
  </Device>
</CMS>

1 个答案:

答案 0 :(得分:0)

[XmlRoot(ElementName = "Device")]
public class Device
{
    [XmlAttribute(AttributeName = "TB")]
    public string TB { get; set; }
    [XmlAttribute(AttributeName = "properties")]
    public string Properties { get; set; }
}

[XmlRoot(ElementName = "PortA")]
public class PortA
{
    [XmlElement(ElementName = "Device")]
    public Device Device { get; set; }
    [XmlAttribute(AttributeName = "Connected_BY")]
    public string Connected_BY { get; set; }
}

[XmlRoot(ElementName = "PortB")]
public class PortB
{
    [XmlAttribute(AttributeName = "Connected_BY")]
    public string Connected_BY { get; set; }
}

[XmlRoot(ElementName = "PortE")]
public class PortE
{
    [XmlElement(ElementName = "Device")]
    public Device Device { get; set; }
    [XmlAttribute(AttributeName = "Connected_BY")]
    public string Connected_BY { get; set; }
}

[XmlRoot(ElementName = "CMS")]
public class CMS
{
    [XmlElement(ElementName = "Device")]
    public Device Device { get; set; }
}