从ChildNodes获取具有特定名称的InnerXML / InnerText。最佳实践

时间:2014-05-20 17:32:31

标签: c# xml serialization xml-parsing

我有一个看起来像这样的(缩短的)

 <TrainingCenterDatabase>
  <Activities>
    <Activity Sport="Running">
      <Id>2014-04-28T23:54:41.000Z</Id>
      <Lap StartTime="2014-04-28T23:54:41.000Z">
        <TotalTimeSeconds>284.957</TotalTimeSeconds>
        <DistanceMeters>1000.0</DistanceMeters>
        <MaximumSpeed>4.160999774932861</MaximumSpeed>
        <Calories>67</Calories>
        <AverageHeartRateBpm>
           <Value>152</Value>
        </AverageHeartRateBpm>
        <MaximumHeartRateBpm>
           <Value>162</Value>
        </MaximumHeartRateBpm>
        <Intensity>Active</Intensity>
        <TriggerMethod>Manual</TriggerMethod>
  </Lap>
  <Lap>
     SAME STUFF HERE
 </Lap>
</Activity>
  <Activities>
 </TrainingCenterDatabase>

我以这种方式提取信息:

        XmlNodeList lapList = doc.GetElementsByTagName("Lap");

        activity = new Activity();

        foreach (XmlNode lap in lapList)
        {
            var split = new Lap
            {
                StartTime = DateTime.Parse(lap.Attributes[0].Value),
                LapDistance = ConvertToDouble(lap.ChildNodes.Item(1).InnerXml),
                LapMaximunSpeed = ConvertToDouble(lap.ChildNodes.Item(2).InnerXml),
                LapCalories = ConvertToInt(lap.ChildNodes.Item(3).InnerXml),
                LapAverageHeartRate = ConvertToInt(lap.ChildNodes.Item(4).InnerText),
                LapMaximumHeartRate = ConvertToInt(lap.ChildNodes.Item(5).InnerText),
            };

我的问题是,有没有办法减少错误?喜欢(引用元素名称?):

LapDistance = ConvertToDouble(lap.ChildNodes.Item["DistanceMeters"].InnerXml),

这种情况的最佳做法是什么?

1 个答案:

答案 0 :(得分:1)

您可以使用SelectSingleNode()和适当的XPath字符串作为参数来按节点名称选择子节点,例如:

LapDistance = ConvertToDouble(lap.SelectSingleNode("DistanceMeters").InnerXml)

如果您不确定所有<Lap>节点都有相应的子元素,则需要进行空检查。