我正在创建要在后续步骤中读取的 XML 索引文件。我有可变长度数组,我将它们写入一个文件。
有一个问题,我认为它在阅读器代码内部。由于某种原因,TimeStamp 和 Long 元素被正确读入数组,但 Lat 和 VideoFile 元素被跳过。由于某种原因,他们的 reader.nodetype 永远不会返回。read() 方法获取它们的唯一方法是在 TEXT 节点类型中,然后它只显示 innerxml 值,这对我来说没用。
保存 XML 文件的示例后,下面的代码应该可以完全运行。
再次感谢堆栈用户。
创建
using System.Xml;
XmlTextWriter xmlwriter = new XmlTextWriter(file, null);
xmlwriter.Formatting = Formatting.Indented;
//xmlwriter.Indentation = 4;
xmlwriter.WriteStartDocument();
xmlwriter.WriteStartElement("Index");
for (int i = 0; i < malLat.Count; i++)
{
xmlwriter.WriteStartElement("Marker");
xmlwriter.WriteStartElement("TimeStamp");
xmlwriter.WriteString(malTimes[i].ToString());
xmlwriter.WriteEndElement();
xmlwriter.WriteStartElement("Lat");
xmlwriter.WriteString(malLat[i].ToString());
xmlwriter.WriteEndElement();
xmlwriter.WriteStartElement("Long");
xmlwriter.WriteString(malLong[i].ToString());
xmlwriter.WriteEndElement();
xmlwriter.WriteStartElement("VideoFile");
xmlwriter.WriteString(malVideoTitle[i].ToString());
xmlwriter.WriteEndElement();
xmlwriter.WriteEndElement();
}
xmlwriter.WriteEndElement();
xmlwriter.WriteEndDocument();
xmlwriter.Close();
阅读
using System.Xml;
XmlTextReader lxmlReader = new XmlTextReader(mstrIndexFile + ".xml");
lxmlReader.WhitespaceHandling = WhitespaceHandling.None;
while (lxmlReader.Read())
{
if (lxmlReader.NodeType == XmlNodeType.Element)
{
if (lxmlReader.Name == "TimeStamp")
{
malTimes.Add(lxmlReader.ReadInnerXml().ToString());
}
else if (lxmlReader.Name == "Lat")
{
malLat.Add(lxmlReader.ReadInnerXml().ToString());
}
else if (lxmlReader.Name == "Long")
{
malLong.Add(lxmlReader.ReadInnerXml().ToString());
}
else if (lxmlReader.Name == "VideoFile")
{
malVideoTitle.Add(lxmlReader.ReadInnerXml().ToString());
}
}
}
lxmlReader.Close();
XML 文档示例
<Index>
<Marker>
<TimeStamp>2011-7-17 23:18:39</TimeStamp>
<Lat>-121.261953323166</Lat>
<Long>43.0594755392741</Long>
<VideoFile>C:\Users\kpenner\Desktop\Video Dev\1_1.wmv</VideoFile>
</Marker>
<Marker>
<TimeStamp>2011-7-17 23:18:40</TimeStamp>
<Lat>-122.260755</Lat>
<Long>46.05878</Long>
<VideoFile>C:\Users\kpenner\Desktop\Video Dev\1_1.wmv</VideoFile>
</Marker>
</Index>