未从XML节点读取两个值

本文关键字:两个 XML 节点 读取 未从 | 更新日期: 2023-09-27 18:24:01

我有这个XML

 <?xml version="1.0" encoding="UTF-8"?>
 <nfeProc xmlns="http://www.portalfiscal.inf.br/nfe" versao="2.00">-<NFe>-<infNFe   versao="2.00" Id="NFe35130649196462000115550010000036141000025758">
  <ide>
  <natOp>DEVOL. ARMAZENAGEM</natOp>
  </ide>
  <total>
        <ICMSTot>
         <vNF>43778.00</vNF>
        </ICMSTot>
 </total>

我用这个C#代码阅读:

  private void leerarquivoN(string caminx)
    {
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load(caminx);
        XmlNodeList ml = xmlDoc.GetElementsByTagName("*");
        XmlNode primer = xmlDoc.DocumentElement;
        tipo_arq = primer.Name;
        if (xmlDoc.DocumentElement.Name == "nfeProc")
        {  foreach (XmlNode xn in ml)
            {
                if (xn.Name == "infNFe")
                {
                    chave_nota = xn.Attributes["Id"].Value;
                    versao = xn.Attributes["versao"].Value;
                    lblChaveNota.Text = chave_nota; lblversao.Text = versao;
                }
             }
             XmlNodeList xnList = xmlDoc.GetElementsByTagName("ide");
             foreach (XmlNode xn in xnList)
             {
                 if (xn.Name == "ide")
                 {
                     if (xn["nNF"] != null)
                     { nnota = (xn["nNF"]).InnerText; label8.Text = nnota; }
                     if (xn["dEmi"] != null)
                     { ndata = (xn["dEmi"]).InnerText; lblData.Text = ndata;}
                     if (xn["natOP"] != null)
                     { natop = (xn["natOP"]).InnerText; lblNAtop.Text = natop ; }
                  }
             }
              XmlNodeList xnList2 = xmlDoc.GetElementsByTagName("emit");
              foreach (XmlNode xn in xnList2)
              {
                  {   if (xn["CNPJ"] != null)
                      { ncnpj = (xn["CNPJ"]).InnerText; lblCNPJ.Text  = ncnpj; }
                    }
              }
              XmlNodeList xnList3 = xmlDoc.GetElementsByTagName("total");
              foreach (XmlNode xn in xnList3)
              {
                  {
                      if (xn["vNF"] != null)
                      { ntotal  = (xn["vNF"]).InnerText; lblvNF.Text = ntotal ; }
                  }
              }

        }  

我不会读VNF和natOP,我做错了什么???感谢

未从XML节点读取两个值

您正在使用的代码只获取主节点。要获得与每个节点关联的子节点(natOpvNF),必须依赖不同的代码(MSDN参考)。natOp样本(循环xnList内部):

if (xn.HasChildNodes)
{
    for (int i=0; i<xn.ChildNodes.Count; i++)
    {
      //xn.ChildNodes[i].InnerText -> what you are after
    }
}