我有以下Xml结构:
<event id="0" start_time="2014-05-21 10:00:00" duration="86340">
<short_event_descriptor lang="alb" name="Programet e Kanalit A1">Programe/Emisione</short_event_descriptor>
<extended_event_descriptor lang="alb">
<text>Programet dhe Emisionet e perditshme te kanalit A1</text>
</extended_event_descriptor>
</event>
<event id="1" start_time="2014-05-22 10:00:00" duration="86340">
<short_event_descriptor lang="alb" name="Programs of Channel A1">Programs/TalkShows</short_event_descriptor>
<extended_event_descriptor lang="alb">
<text />
</extended_event_descriptor>
</event>
我正在尝试的代码如下:
try
{
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element: // The node is an element.
if (reader.Name == "channel")
{
while (reader.MoveToNextAttribute())
{
if (reader.Name == "name")
{
// epg = new epg2();
epg.channelname = reader.Value;
epg.number = Convert.ToInt32(channelNames[i][1]);
xmlfile.Add(epg);
}
}
}
if (reader.Name == "event")
{
while (reader.MoveToNextAttribute())
{
if (reader.Name == "start_time")
{
// Ev = new Event();
Ev.starttime = Convert.ToDateTime(reader.Value);
}
else if (reader.Name == "duration")
{
Ev.duration = Convert.ToInt32(reader.Value);
}
else if (reader.Name == "name")
{
Ev.duration = Convert.ToInt32(reader.Value);
}
}
}
if (reader.Name == "short_event_descriptor")
{
while (reader.MoveToNextAttribute())
{
if (reader.Name == "name")
{
Ev.name = reader.Value;
}
}
}
break;
case XmlNodeType.Text: //Display the text in each element.
if (shenjuar > 0)
{
try
{
Ev.shortDescription = reader.Value.Replace("\r\n", "").Replace("\r", "").Replace("\n", "").Replace("Sub. Ang", "").Replace("Sub. Alb", "").Replace('\"', '\''); ;
}
catch
{
Ev.shortDescription = reader.Value;
}
shenjuar *= -1;
}
else if (shenjuar < 0)
{
try
{
Ev.longDescription = reader.Value.Replace("\r\n", "").Replace("\r", "").Replace("\n", "").Replace("Sub. Ang", "").Replace("Sub. Alb", "").Replace('\"', '\''); ;
}
catch
{
Ev.longDescription = reader.Value;
}
shenjuar *= -1;
epg.EventNumber.Add(Ev);
}
else reader.Skip();
break;
case XmlNodeType.EndElement: //Display the end of the element
reader.Skip();
break;
}
}
xmlfile.Add(epg);
}
catch (FileNotFoundException fnfe)
{
TextBox1.Text = "Error. Can not find " + CName + ".xml file";
//return;
}
catch (Exception exc)
{
TextBox1.Text = "Unknown Error: \r\nError on " + CName + ".xml file \r\n Error Description:" + exc.Message;
//return;
}
}
关键是这段代码用于XML文件列表,问题是对于某些文件,标签是自动关闭的,在这种情况下,读者会跳过阅读。由于XML文件作为标准提供给公司并且每天都在更改其内容,因此我无法更改其结构。我试图使用IsEmptyElement属性,我尝试了不同的方法来读取数据,但无论如何,它总是跳过带有空标记的文件。已经有一个星期了,我正在尝试我能找到的每一个教程,但没有处理工作
答案 0 :(得分:0)
您的代码会跳过text
元素:
if (reader.IsStartElement("text"))
reader.Skip();
删除它并使用XmlReader.IsEmptyElement
检查自关闭元素。