Xml problem in finding a particular element when reading
Hi guys.
What it the best way to do this?
I Have an xml file in this format
<Countries>
<Country>
<ID>1</ID>
<Name>Italy</Name>
</Country>
<Country>
<ID>2</ID>
<Name>France</Name>
</Country>
<Country>
<ID>3</ID>
<Name>England</Name>
</Country>
</Countries>
Now i need a way to find if a particular Name exists in the xml and return true
public Function IsCountryInXmlFile (byval countryName as string)as boolean
'//Read the xml file and find if the country exists
'//HOW DO I DO THIS
return isCountyInXmlFile
end function
I dont seem to find a way to do it using the XmlReaderSettings.
Could somebody give me an example?
Thanks a lot
Hello,
There can be many ways. You can use XMLDocument class for all sorts of reading and I think XMLDocument is a wonderful class. I have modified your function, just replace the path for your XML File or if you have your XML in a tring you can use doc.LoadXML() function instead of doc.Load()
There can be other ways also, for example you can use doc.SelectNodes() with an XPath Expression to select nodes instead of doc.GetElementByTagName(). I hope the Following function will serve your purpose
| |
Public Function IsCountryInXmlFile(ByVal countryName As String) As Boolean Dim doc As New XmlDocument Dim nodeList As XmlNodeList Try doc.Load("C:\\doc.xml") nodeList = doc.GetElementsByTagName("Name") For Each node As XmlNode In nodeList If node.FirstChild.Value = countryName Then Return True End If Next Return False Catch ex As Exception End Try End Function |
Regards,
Aleem
The easiest way would be to use an XmlDocument and then just go
XmlNode TmpNode = XmlDocument.SelectSingleNode("//Country[Name='" + CountryToFind + "'");
if (TmpNode==null) { return false; } else { return true; }
Guys,
Thanks for the very good response .I am trying to get to grip with xml .
I will play with suggested answer .
I think i might have missed to ask something important.
Let's assume i want to find in my xml file whether a country exists.
How can I return all the elements- attributes that are associated with it?
Has anybody written a generic function where you pass an ID or countryName whatever and returns all the stuff regarding that ID or countryName?
thanks a lot for replying