XmlReader获取值而不移动光标前进

时间:2018-04-28 09:37:43

标签: c# .net xml xmlreader

这是在Boston[,-"medv"]向前移动光标时跳过行。 reader.ReadString()是空的。

如何将此XML读入reader.Value

List<LogData> logDatas = new List<LogData>();

1 个答案:

答案 0 :(得分:2)

不确定您希望当前代码做什么,但是要将给定的xml解析为给定的数据结构,以下似乎是合理的方法:

public static List<LogData> GetLogDatas(string xml) {
    List<LogData> logDatas = new List<LogData>();
    // no need for waste file, use StringReader
    using (var sreader = new StringReader(xml))
    using (XmlReader reader = XmlReader.Create(sreader)) {
        LogData currentData = null;
        while (reader.Read()) {
            if (reader.IsStartElement("logData")) {
                // we are positioned on start of logData
                if (currentData != null)
                    logDatas.Add(currentData);
                currentData = new LogData(reader.GetAttribute("id"));
            }
            else if (reader.IsStartElement("data")) {
                // we are on start of "data"
                // we always have "currentData" at this point                        
                Debug.Assert(currentData != null);
                reader.ReadToFollowing("index");
                var index = int.Parse(reader.ReadElementContentAsString());
                // check if we are not already on "value"
                if (!reader.IsStartElement("value"))
                    reader.ReadToFollowing("value");
                var value = double.Parse(reader.ReadElementContentAsString(), CultureInfo.InvariantCulture);
                currentData.LogPoints.Add(new LogPoint(index, value));
            }
        }

        if (currentData != null)
            logDatas.Add(currentData);
    }

    return logDatas;
}