I am working on a little USPS tracking class, very simple calls web api returns xml, parses the xml to an object, passes that object back via an event.
for some reason I can't seem to get the XML to parse correctly. I there are an unknown amount of a certain node in the root node, so deserialization is out, but using XMLReader I can only get the first value from the TrackDetails nodes.
Here is the xml example
<?xml version="1.0"?>
<TrackResponse><TrackInfo ID="EJ958088694US"><TrackSummary>
Your item was delivered at 1:39 pm on June 1 in WOBURN MA 01815.
</TrackSummary><TrackDetail>
May 30 7:44 am NOTICE LEFT WOBURN MA 01815.
</TrackDetail><TrackDetail>
May 30 7:36 am ARRIVAL AT UNIT NORTH READING MA 01889.
</TrackDetail><TrackDetail>
May 29 6:00 pm ACCEPT OR PICKUP PORTSMOUTH NH 03801.
</TrackDetail></TrackInfo></TrackResponse>
no problem getting the ID from the attribute or the track summary, but I can't seem to get all the trackDetails, I get the first one, but never any of the others. I don't do much xml parsing and normally I just use serialization. So this is proving problematic for me.
some Code i have tried
using (XmlReader reader = XmlReader.Create(new StringReader(e.Result)))
{
reader.MoveToContent();
while (reader.Read())
{
if (reader.IsStartElement())
{
switch (reader.Name)
{
case "TrackInfo":
reader.MoveToFirstAttribute();
Pack.PackageID = reader.Value;
break;
case "TrackSummary":
Pack.TrackingSummary = reader.ReadElementContentAsString();
break;
case "TrackDetail":
Pack.TrackingDetails.Add(new TrackingDetail(reader.ReadElementContentAsString()));
break;
default:
reader.Skip();
break;
}
}
}
or
using (XmlReader reader = XmlReader.Create(new StringReader(e.Result)))
{
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
if (reader.Name == "TrackInfo")
{
reader.MoveToFirstAttribute();
Pack.PackageID = reader.Value;
}
else if (reader.Name == "TrackSummary")
{
Pack.TrackingSummary = reader.ReadElementContentAsString();
}
else if (reader.Name == "TrackDetail")
{
Pack.TrackingDetails.Add(new TrackingDetail(reader.ReadElementContentAsString()));
}
}
}
}
even tried
using (XmlReader reader = XmlReader.Create(new StringReader(e.Result)))
{
reader.ReadToFollowing("TrackInfo");
reader.MoveToFirstAttribute();
Pack.PackageID = reader.Value;
reader.ReadToFollowing("TrackSummary");
Pack.TrackingSummary = reader.ReadElementContentAsString();
while (reader.ReadToNextSibling("TrackDetail"))
{
Pack.TrackingDetails.Add(new TrackingDetail(reader.ReadElementContentAsString()));
}
}
all of them run without error, showing the tracking summary, the ID and 1 of the 3 trackdetails, But none of them show all three, and not knowing how many may be there, its important that all of them are there.
So what am I doing wrong?
note: Pack is just an instance of a class that holds all the data as strings.