将此xml文件转换为我的对象

时间:2014-04-09 09:37:27

标签: c# xml deserialization

这类似于What is the easiest way to convert this XML document to my object?之类的问题,但我认为还有一些额外的复杂性。

我想从这个xml中获取以下对象。但是,因为我的Bean类需要的东西是类似命名的子元素而不是属性,因为部件和集合有点混乱。我不完全确定如何处理这个问题。

XML,我在XDocument中有

<bean class="com.nathan.etc.etc">
  <property name="documentName" value="\\myfilepath" />
  <property name="containerNames">
    <list>
      <value>One</value>
      <value>Two</value>
    </list>
  </property>
  <property name="partNames">
    <list>
        <list>
            <value>First Part of One</value>
            <value>Second Part of One</value>
        </list>
        <list>
            <value>First Part of Two</value>
            <value>Second Part of Two</value>
        </list>
    </list>
  </property>   
</bean>

C#代码

class Bean {

    public string FilePath {get; set;}   //eg "\\myfilepath"

    public List<Container> Containers {get; set;}

}

class Container {

    public string Name {get; set;}  //eg "One"

    public List<Part > Parts {get; set;}

}

class Part {

    public string Name {get; set;}   //eg "First Part of One"

}

1 个答案:

答案 0 :(得分:1)

我正在为XmlDocument撰稿,但您可以轻松适应XDocument

var xmlDoc = new XmlDocument();
// ... load it

var bean = new Bean{ Containers = new List<Container>() };
bean.FilePath = xmlDoc.SelectSingleNode("/bean/property[@name='documentName']")
                      .GetAttribute("value");
int index = 1;
foreach(XmlElement xmlContainer in xmlDoc.SelectNodes(
           "/bean/property[@name='containerNames']/list/value"))
{
    var container = new Container
    { 
        Name  = xmlContainer.InnerText,
        Parts = new List<Part>()
    };

    foreach(XmlElement xmlPart in xmlDoc.SelectNodes(String.Format(
           "/bean/property[@name='partNames']/list/list[{0}]/value", index)))
    {
        var part = new Part{ Name = xmlPart.InnerText };
        container.Parts.Add(part);
    }

    bean.Containers.Add(container);
    index++;
}