Reading an XMLFile

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hello all,

In the below XML:

- <comment_list description="Comment list">
- <comment description="Comment" item_no="1">
<date description="Date">2006-09-27</date>
<author description="Author">HKGE0406505.001</author>
<visible_to description="Visible to">P</visible_to>
<comment description="Comment">086095.</comment>
</comment>
- <comment description="Comment" item_no="2">
<date description="Date">2006-09-27</date>
<author description="Author">E0760.116</author>
<visible_to description="Visible to">P</visible_to>
<comment description="Comment">time adjuster</comment>
</comment>
</comment_list>

and using the below code

using (XmlReader reader = XmlReader.Create(@"c:\xml\isn_prod.XML-0139.xml"))
{
reader.MoveToContent();

reader.ReadToDescendant("claimkey");
sb.Append("ClaimKey: " + reader.GetAttribute("id"));

reader.ReadToFollowing("comment_list");


reader.ReadToDescendant("comment");

reader.ReadToDescendant("date");
sb.Append(" Date: " +
reader.ReadElementContentAsString());
sb.Append(" Author: " +
reader.ReadElementContentAsString());

reader.ReadToFollowing("visible_to");
sb.Append(" visible to: " +
reader.ReadElementContentAsString());

sb.Append(" comment: " +
reader.ReadElementContentAsString());

string a = sb.ToString();

}

I can happily navigate comment item number 2, but I can't seem to find a way
to get to the comment nodes (id=2).

Any help would be great,

Thanks,

Jon
 
Hi Jon,

I prefer XmlDocument and selecting nodes using XPath queries when reading
xml, so below is an alternative solution.

Claimkey is not in your sample xml so I don't know where it would be.

XmlDocument doc = new XmlDocument();
doc.LoadXml(@"c:\xml\isn_prod.XML-0139.xml");

XmlNodeList list = doc.SelectNodes("/comment_list/comment");

foreach (XmlNode node in list)
{
sb.AppendLine("Date: " + node["date"].InnerText);
sb.AppendLine("Author: " + node["author"].InnerText);
sb.AppendLine("Visible to: " + node["visible_to"].InnerText);
sb.AppendLine("Comment: " + node["comment"].InnerText);
}

If you just want a single comment node based on its item_no attribute, use

XmlNode node =
doc.SelectSingleNode("/comment_list/comment[@item_no='2']");
 
Back
Top