2010-06-03 5 views
2

Comment puis-je trouver la valeur par nom de tag dans le fichier xml? using C# .net 2.0trouver la valeur par nom de tag dans xml

Il y a juste 10 noeuds distincts dans mon xmldocument.

Je ne veux pas écrire xpath. Je pense qu'il y a une propriété de recherche automatique.

Répondre

0

J'ai résolu mon problème avec cette scneirao:

XmlNodeList nl = xdoc.GetElementsByTagName ("CustomerID"); sb.Append (nl [0] .InnerXml);

0

Impossible de se souvenir de la syntaxe exacte, mais d'écrire une requête Xpath, puis d'utiliser XPathNavigator.Select pour le trouver. Edit: Rappelez-vous, je pense que c'est quelque chose comme //@tagname, donc si vous faites XPathNavigator.Select("//@tagname") je pense que cela fonctionnerait. En supposant qu'avec tag, vous voulez dire un attribut, si vous cherchez des éléments, il devrait simplement être //tagname.

0

voir cette fonction complète get valeur de nœud ainsi que la valeur d'attribut du fichier xml ...

public string GetXmlNodeValue(string xmlfilePath, string TagName, string Attribute) 
{ 
    XmlDocument objXML = new XmlDocument(); 
    bool IsNodeValuefound = false; 
    string Value = string.Empty; 
    try 
    { 
     if (File.Exists(xmlfilePath)) 
     { 
      objXML.Load(xmlfilePath); 

      XmlNode xNode = objXML.DocumentElement.FirstChild; 
      while (xNode != null) 
      { 
       if (string.Compare(xNode.Name, TagName, true) == 0) 
       { 
        if (!string.IsNullOrEmpty(Attribute)) 
        { 
         if (xNode.Attributes.GetNamedItem(Attribute) != null) 
         { 
          IsNodeValuefound = true; 
          Value = xNode.Attributes.GetNamedItem(Attribute).Value; 
         } 
        } 
        else 
        { 
         IsNodeValuefound = true; 
         Value = xNode.InnerText.Trim(); 
        } 
       } 
       xNode = xNode.NextSibling; 
      } 
     } 
     if (IsNodeValuefound) 
      return Value; 
     else 
      return string.Empty; 
    } 
    catch (XmlException xmlEx) 
    { 
     throw xmlEx; 
    } 
    catch (Exception ex) 
    { 
     throw ex; 
    } 
    finally 
    { 
     objXML = null; 
    } 
}  
+0

merci mais je ne veux pas utiliser beaucoup de lignes de code. Tout comme GetElementByID et atteignant sa valeur – Jack

+0

si résolu votre problème .. s'il vous plaît marquer comme réponse. – Harendra

0

Exemple simple:

XmlDocument xmlDoc = new XmlDocument(); 
xmlDoc.LoadXml(someRawData); 
XmlNodeList yourNodes = xmlDoc.GetElementsByTagName("YourTagName"); 

Ensuite, vous pouvez itérer yourNodes et prend les valeurs.

Questions connexes