如何读取这部分的web XML文件

本文关键字:web XML 文件 这部分 何读取 读取 | 更新日期: 2023-09-27 18:08:28

我正在开发一个XML阅读器,它在标签中显示结果。我想读一下Opmerking这个节点它位于Opmerkingen中一个例子:

<VertrekkendeTrein>
 <RitNummer>4085</RitNummer>
 <VertrekTijd>2014-06-13T22:00:00+0200</VertrekTijd>
 <EindBestemming>Rotterdam Centraal</EindBestemming>
 <TreinSoort>Sprinter</TreinSoort>
 <RouteTekst>A'dam Sloterdijk, Amsterdam C., Duivendrecht</RouteTekst> 
 <Vervoerder>NS</Vervoerder>
 <VertrekSpoor wijziging="false">4</VertrekSpoor>
 <Opmerkingen>
  <Opmerking> Rijdt vandaag niet</Opmerking>
 </Opmerkingen>
</VertrekkendeTrein>

"Opmerkingen"并不总是在那里,它总是在变化。我现在使用的代码:

XmlNodeList nodeList = xmlDoc.SelectNodes("ActueleVertrekTijden/VertrekkendeTrein/*");

:

foreach (XmlNode nodelist2 in nodeList)
{
    if (i < 17) //4
    {
        switch (nodelist2.Name)
        {
            case "VertrekTijd": string kuttijd4 = (nodelist2.InnerText);
            var res4 = Regex.Match(kuttijd4, @"'d{1,2}:'d{1,2}").Value;
            lblv4.Text = Convert.ToString(res4); break;
            case "TreinSoort": lblts4.Text = (nodelist2.InnerText); break;
            case "RouteTekst": lblvia4.Text = (nodelist2.InnerText); break;
            case "VertrekSpoor": lbls4.Text = (nodelist2.InnerText); i++; break;
        }
    }
}

如何读取"Opmerking"部分并将其设置在一个case中?我试了几次,但都失败了。我也试过:

case "Opmerking": var texeliseeneiland1 = (nodelist2.InnerText); if (texeliseeneiland1 == null) { } else { lblop1.Text = texeliseeneiland1; lblop1.Font = new Font(lblop1.Font.FontFamily, 17); lblop1.Visible = true; picop1.Visible = true; }; break;

谁知道答案?

如何读取这部分的web XML文件

只需扩展您的逻辑,检查当前节点是否有子节点,如果有,读取它们并处理:

if (nodelist2.HasChildNodes)
{
  for (int i=0; i<nodelist2.ChildNodes.Count; i++)
  {
    var childNode = root.ChildNodes[i];
    //do whatever you need to display the contents of the child node. 
  }
}

我还建议考虑使用LinqToXML,或者至少重构您共享的代码。使用LinqToXML可能像这样简单:

var temp = from remarkNode in nodelist2.Descendants("Opmerking")
           select remarkNode.Value;

以某种方式将xml内容加载到XDocument对象中并遍历它。示例:从文件

中读取
 var doc = XDocument.Load("C:/test.xml");
 foreach (var xe in doc.Descendants("Opmerking"))
 {
     var value = xe.Value;
     //Do your job with value
 }