Reputation: 6531
This is similar to questions like What is the easiest way to convert this XML document to my object?, but i think has some additional complexity.
I would like to get the below objects out of this xml. However, because things I need for my Bean class are in similarly named sub elements rather than attributes and since parts and collections are a bit of a mess. I'm not entirely sure how to approach this.
XML, which I have in an 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# code
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"
}
Upvotes: 0
Views: 192
Reputation: 57936
I'm writing for a XmlDocument
, but you can easily adapt for a 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++;
}
Upvotes: 1