2011-12-13 24 views
10

¿Cómo puedo verificar si un nodo tiene un atributo particular o no?Compruebe si el nodo Xml tiene un atributo

Lo que hice es:

string referenceFileName = xmlFileName; 
XmlTextReader textReader = new XmlTextReader(referenceFileName); 

while (textReader.Read()) 
{ 
    XmlNodeType nType = textReader.NodeType; 

    // if node type is an element 
    if (nType == XmlNodeType.Element) 
    { 
    if (textReader.Name.Equals("Control")) 
    { 
     if (textReader.AttributeCount >= 1) 
     { 
     String val = string.Empty; 
     val = textReader.GetAttribute("Visible"); 
     if (!(val == null || val.Equals(string.Empty))) 
     { 

     } 
     } 
    } 
    } 

¿Hay alguna función para comprobar que un determinado atributo está presente o no?

+3

La palabra es "verificar", no "chk". – Oded

Respuesta

13

No, no creo que haya ningún método en la clase XmlTextReader que le puede decir si existe un atributo particular o no.

Usted puede hacer una cosa para comprobar

if(null == textReader.GetAttribute("Visible")) 
{ 
    //this means attribute doesn't exist 
} 

porque MSDN dice acerca GetAttribute método

Return the value of the specified attribute. If the attribute is not found, 
a null reference (Nothing in Visual Basic) is returned. 
+0

¿Puede sugerir cualquier otra clase que tenga un método para verificar si existe un atributo en particular o no? –

+0

No en mi conocimiento. No conozco ningún método que devuelva valor bool sobre si el atributo existe o no. Todo lo que sé devuelve nulo si el atributo no existe –

+0

muchas gracias por su ayuda –

2

Pruebe LINQ to XML (consulta a continuación podría requerir correcciones menores ya que no estoy tengo XML que está utilizando)

XDocument xdoc = XDocument.Load("Testxml.xml"); 

// It might be that Control element is a bit deeper in XML document 
// hierarchy so if you was not able get it work please provide XML you are using 
string value = xdoc.Descendants("Control") 
        .Where(d => d.HasAttributes 
           && d.Attribute("Visible") != null 
           && !String.IsNullOrEmpty(d.Attribute("Visible").Value)) 
        .Select(d => d.Attribute("Visible").Value) 
        .Single(); 
8

encontré esto: http://csharpmentor.blogspot.co.uk/2009/05/safely-retrive-attribute-from-xml-node.html

Se puede convertir el XmlNode a un XmlElement a continuación, utilizar el Método HasAttribute para verificar. Lo probé y funciona, es muy útil.

Lo siento no es un ejemplo usando su código - ¡Tengo prisa pero espero que ayude a los futuros encuestados!

+3

Esta respuesta está muy subestimada. Este enlace también vale la pena echarle un vistazo. +1 – Robino

+2

+1 de mí también. Me dio la idea de la siguiente construcción para utilizar en un método-llamada que necesita la cadena o vacío si el atributo existe: '(nodo como XmlElement) .HasAttribute (" nombre2 ")? node.Attributes ["name2"]. Value: String.Empty' – St0fF

0

// Comprobar valor del elemento XML si existe utilizando XmlReader

 using (XmlReader xmlReader = XmlReader.Create(new StringReader("XMLSTRING"))) 
     { 

      if (xmlReader.ReadToFollowing("XMLNODE")) 

      { 
       string nodeValue = xmlReader.ReadElementString("XMLNODE");     
      } 
     }  
0

Tomando refernce de la respuesta de Harish, siguiente código trabajó para mí

XmlTextReader obj =new XmlTextReader("your path"); 
    //include @before"" if its local path 
     while (obj.Read()) { 
     Console.WriteLine(obj.GetAttribute("name")); 
     obj.MoveToNextAttribute(); 
     } 
0

Si alguien no está usando un lector y sólo un XmlDocument intente XmlAttributeCollection/XmlAttribute

XmlDocument doc = new XmlDocument(); 
try{ 
doc.Load(_indexFile); 
    foreach(XmlNode node in doc.DocumentElement.ChildNodes){ 
     XmlAttributeCollection attrs = node.Attributes; 
     foreach(XmlAttribute attr in attrs){ 
      Console.WriteLine(node.InnerText + ": " + attr.Name + " - " + attr.Value); 
      if(attr.Name == "my-amazing-attribute") 
      { 
       //Do something with attribute 
      } 
     } 
    } 
} 
} catch (Exception ex) { 
    //Do something with ex 
} 
Cuestiones relacionadas