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.
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.
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
.
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;
}
}
Simple example:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(someRawData);
XmlNodeList yourNodes = xmlDoc.GetElementsByTagName("YourTagName");
Then you can iterate through yourNodes and takes the values.
I have solved my problem with this scneirao:
XmlNodeList nl = xdoc.GetElementsByTagName("CustomerID"); sb.Append(nl[0].InnerXml);