Right now I have my code similar to this (actually one level deeper). If the company name is equal to the node of company then create a node list from it (as I need to populate a drop down box with all of the details) ---Not using 3.5开发者_如何学C for this project :(
XmlNodeList elemList = xmlDoc.GetElementsByTagName("company");
foreach (XmlNode node in elemList)
{
if (node.Attributes[0].Value == company)
{
foreach (XmlNode child in node.ChildNodes)
{
foreach (XmlNode detail in child.ChildNodes)
{
ddlCodes.Items.Add(detail.Value.ToString());
}
}
}
}
Not really liking all those foreach
statements, just wondering if there is a cleaner way. Here is how my xml looks like
<companies>
<company id="company1">
<code>12</code>
<detail>detail of 12 code</detail>
</company>
<company id="company2">
<code>15</code>
<detail>detail of 15 code</detail>
</company>
</companies>
Have a look at XPath
and the XPathNavigator
class, it provides you with a query language for XML
Or you could use Linq to XML if you want but that depends on the .net framework you're using.
How about this?
[XmlRoot("companies")]
public class Root
{
[XmlElement("company")]
public company[] companies;
}
public class company
{
[XmlAttribute("id")]
public string id;
public string code;
public string detail;
}
XmlSerializer xml = new XmlSerializer(typeof(Root));
Root r = (Root)xml.Deserialize(new StringReader(xmlstr));
精彩评论