tags:

views:

168

answers:

4

How can I find value by tag name in xml file? using C#.net 2.0

There are just 10 distinct nodes in my xmldocument.

I dont want to write xpath. I think there is an auto find property.

A: 

Can't remember the exact syntax, but write an Xpath query and then use XPathNavigator.Select to find it.

Edit: Just remember, I think it's something like //@tagname, so if you do XPathNavigator.Select("//@tagname") I think it would work. Assuming that with tag you mean an attribute, if you're looking for elements it should just be //tagname.

ho1
A: 

see this complete function get node value as well as attribute value from xml file...

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;
        }
    }
Harendra
thanks but I dont want to use lots of code lines. Just like GetElementByID and reaching its value
Jack
if solved ur problem.. please mark it as Answer.
Harendra
A: 

Simple example:

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

Then you can iterate through yourNodes and takes the values.

Lukas Šalkauskas
A: 

I have solved my problem with this scneirao:

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

Jack