Check if XML Element exists

后端 未结 13 1551
傲寒
傲寒 2020-12-03 06:20

How can someone validate that a specific element exists in an XML file? Say I have an ever changing XML file and I need to verify every element exists before reading/parsing

相关标签:
13条回答
  • 2020-12-03 07:00

    Not sure what you're wanting to do but using a DTD or schema might be all you need to validate the xml.

    Otherwise, if you want to find an element you could use an xpath query to search for a particular element.

    0 讨论(0)
  • 2020-12-03 07:02

    How about trying this:

    using (XmlTextReader reader = new XmlTextReader(xmlPath))
    {
        while (reader.Read())
        {
            if (reader.NodeType == XmlNodeType.Element)
            { 
                //do your code here
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-03 07:06

    A little bit late, but if it helps, this works for me...

    XmlNodeList NodoEstudios = DocumentoXML.SelectNodes("//ALUMNOS/ALUMNO[@id=\"" + Id + "\"]/estudios");
    
    string Proyecto = "";
    
    foreach(XmlElement ElementoProyecto in NodoEstudios)
    {
        XmlNodeList EleProyecto = ElementoProyecto.GetElementsByTagName("proyecto");
        Proyecto = (EleProyecto[0] == null)?"": EleProyecto[0].InnerText;
    }
    
    0 讨论(0)
  • 2020-12-03 07:08
    if(doc.SelectSingleNode("//mynode")==null)....
    

    Should do it (where doc is your XmlDocument object, obviously)

    Alternatively you could use an XSD and validate against that

    0 讨论(0)
  • 2020-12-03 07:09

    //Check xml element value if exists using XmlReader

              using (XmlReader xmlReader = XmlReader.Create(new StringReader("XMLSTRING")))
               {
    
                   if (xmlReader.ReadToFollowing("XMLNODE")) 
    
                    {
                        string nodeValue = xmlReader.ReadElementString("XMLNODE");                
                    }
                }     
    
    0 讨论(0)
  • 2020-12-03 07:10

    Just came across the same problem and the null-coalescing operator with SelectSingleNode worked a treat, assigning null with string.Empty

     foreach (XmlNode txElement in txElements)
     {
         var txStatus = txElement.SelectSingleNode(".//ns:TxSts", nsmgr).InnerText ?? string.Empty;
         var endToEndId = txElement.SelectSingleNode(".//ns:OrgnlEndToEndId", nsmgr).InnerText ?? string.Empty;
         var paymentAmount = txElement.SelectSingleNode(".//ns:InstdAmt", nsmgr).InnerText ?? string.Empty;
         var paymentAmountCcy = txElement.SelectSingleNode(".//ns:InstdAmt", nsmgr).Attributes["Ccy"].Value ?? string.Empty;
         var clientId = txElement.SelectSingleNode(".//ns:OrgnlEndToEndId", nsmgr).InnerText ?? string.Empty;
         var bankSortCode = txElement.SelectSingleNode(".//ns:OrgnlEndToEndId", nsmgr).InnerText ?? string.Empty; 
    
         //TODO finish Object creation and Upsert DB
      }
    
    0 讨论(0)
提交回复
热议问题