复杂的XML反序列化为C#类

时间:2017-04-21 10:25:19

标签: c# xml xml-parsing deserialization

如何将下面的xml反序列化为c#classes

<Transaction ControlNumber="0001">
    <ST>
        <ST01>271</ST01>
    </ST>
    <BHT>
        <BHT01>022</BHT01>
    </BHT>
    <HierarchicalLoop LoopId="2000A" LoopName="Information Source Level" Id="1" ParentId=""></HierarchicalLoop>
    <HierarchicalLoop LoopId="2000A" LoopName="Information Source Level" Id="2" ParentId=""></HierarchicalLoop>
    <HierarchicalLoop LoopId="2000A" LoopName="Information Source Level" Id="3" ParentId=""></HierarchicalLoop>
</Transaction>

我知道如果HierarchicalLoop节点包含在HierarchicalLoops节点中会很容易,但我别无选择,因为不允许更改XML格式。我正在寻找HierarchicalLoop中包含的Transaction节点的指导,其中Transaction中还有其他不同的子节点!我也使用C#中的XmlSerializer类来解析XML。谢谢!

2 个答案:

答案 0 :(得分:1)

我已经知道了,现在已经解决了。我猜这是一个有点愚蠢的问题。

public class Transaction
{
    [XmlAttribute("ControlNumber")]
    public string ControlNumber { get; set; }

    public ST ST { get; set; }

    public BHT BHT { get; set; }

    [XmlElement("HierarchicalLoop")]
    public List<HierarchicalLoop> HierarchicalLoops { get; set; }
}

答案 1 :(得分:0)

创建一组类:

public class Transaction
{
    public ST ST { get; set; }
    public BHT BHT { get; set; }
    [XmlElement]
    public List<HierarchicalLoop> HierarchicalLoop { get; set; } // maybe HierarchicalLoop[]
    [XmlAttribute]
    public string ControlNumber { get; set; } // maybe int
}
public class ST
{
    public string ST01 { get; set; } // maybe int
}

public class BHT
{
    public string BHT01 { get; set; } // maybe int
}

public class HierarchicalLoop
{
    [XmlAttribute]
    public string LoopId { get; set; }
    [XmlAttribute]
    public string LoopName { get; set; }
    [XmlAttribute]
    public string Id { get; set; } // maybe int
    [XmlAttribute]
    public string ParentId { get; set; }
}

使用示例:

Transaction transaction;
var xs = new XmlSerializer(typeof(Transaction));

using (var fs = new FileStream("in.xml", FileMode.Open))
    transaction = (Transaction)xs.Deserialize(fs);

using (var fs = new FileStream("out.xml", FileMode.Create))
    xs.Serialize(fs, transaction);
相关问题