ASP.NET query a XML file

Hi Experts I have a XML resultset from Google Maps API from this URL http://maps.googleapis.com/maps/api/geocode/xml?address=Leeds%20Train%20Station&sensor=false Hower I only want to return the address component that has a type of postal_code_prefix and postal_code and the formatted_address Is this possible and how? Please find the code I am currently using. It returns everthing
Const URLString As String = "http://maps.googleapis.com/maps/api/geocode/xml?address=Leeds%20Train%20Station&sensor=false"
        Dim reader As XmlTextReader = New XmlTextReader(URLString)
        Do While (reader.Read())
            Select Case reader.NodeType

                Case XmlNodeType.Element 'Display beginning of element.
                    Response.Write("<" & reader.Name)
                    If reader.HasAttributes Then 'If attributes exist
                        While reader.MoveToNextAttribute()
                            'Display attribute name and value.
                            Response.Write("'{0}'='{1}'", reader.Name, reader.Value)
                        End While
                    End If
                    Response.Write(">")

                Case XmlNodeType.Text 'Display the text in each element.
                    Response.Write(reader.Value)
                Case XmlNodeType.EndElement 'Display end of element.
            End Select
        Loop

Open in new window

Untitled-1.png
LVL 1
David CIT Projects ManagerAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Asim NazirCommented:
Hi,

Simple approach can be one of two:
1. Use LINQ to XML
2. Use XPATH to evaluate your expression.

Using XPATH, you can write a expression that can be evaluated using below code:

 
private string ProcessRixml(string sParsingValue, XmlDocument document)
        {
            String sParsedValue = string.Empty;

            // Create a navigator to query with XPath.
            XPathNavigator nav = document.CreateNavigator();

            string namespaceUri = "http://www.rixml.org/2005/3/RIXML";
            XmlNamespaceManager ns = new XmlNamespaceManager(new NameTable());
            ns.AddNamespace("ns", namespaceUri);
            try
            {
                XPathNodeIterator iterator = nav.Select(sParsingValue, ns);
                foreach (XPathNavigator item in iterator)
                {
                    // Get value for the selected expression
                    sParsedValue = item.Value;
                    break;
                }
            }
            catch { }

            return sParsedValue;
        }

Open in new window


Let me know if you need more help.
Asim
Asim NazirCommented:
You can remove namespace related code, if there is no namespace in your document. Coe snippert to remove will be:

string namespaceUri = "http://www.rixml.org/2005/3/RIXML";
            XmlNamespaceManager ns = new XmlNamespaceManager(new NameTable());
            ns.AddNamespace("ns", namespaceUri);
StefanLambdaCommented:
I think you can use Xpath (like this http://www.codeproject.com/KB/cpp/myXPath.aspx)

The first xpath to get the address component  :  //address_component[long_name="LSi 4"]

Hope this help.

Stefan


PMI ACP® Project Management

Prepare for the PMI Agile Certified Practitioner (PMI-ACP)® exam, which formally recognizes your knowledge of agile principles and your skill with agile techniques.

Jorge PaulinoIT Pro/DeveloperCommented:
XML Literals is the easy way to work with XML files. Check this article http://www.experts-exchange.com/Programming/Languages/.NET/Visual_Basic.NET/A_2897-Xml-Literals.html
Asim NazirCommented:
I would like to add to what jpaulino recommended.
XML literals are only supoorted in VB.Net and no other language is supported. Also, Visual Basic compiles XML literals into LINQ to XML objects.
takwirirar, what language are you using?
Asim NazirCommented:
Ok. Sorry. I saw your code and its vb.net.
Asim NazirCommented:
So in VB.Net code will be:

 
Private Function ProcessRixml(sParsingValue As String, document As XmlDocument) As String
	Dim sParsedValue As [String] = String.Empty

	' Create a navigator to query with XPath.
	Dim nav As XPathNavigator = document.CreateNavigator()

	Dim namespaceUri As String = "http://www.rixml.org/2005/3/RIXML"
	Dim ns As New XmlNamespaceManager(New NameTable())
	ns.AddNamespace("ns", namespaceUri)
	Try
		Dim iterator As XPathNodeIterator = nav.[Select](sParsingValue, ns)
		For Each item As XPathNavigator In iterator
			' Get value for the selected expression
			sParsedValue = item.Value
			Exit For
		Next
	Catch
	End Try

	Return sParsedValue
End Function

Open in new window

David CIT Projects ManagerAuthor Commented:
I am using VB.NET
Asim NazirCommented:
Ok. So you can use any of the approaches mentioned above.
David CIT Projects ManagerAuthor Commented:
Hi guys these look to be very good solutions however I cant actually make sense of them because I'm still a beginner. Could you help with examples with http://maps.googleapis.com/maps/api/geocode/xml?address=Leeds%20Train%20Station&sensor=false returning the address component that has a type of postal_code_prefix and postal_code and the formatted_address?
StefanLambdaCommented:
The following code iterate the nodes inside the <address_component> having a  long_name = LS1 4
Is it ok for you?

Stefan
Private Sub DotIt()
        Const URLString As String = "http://maps.googleapis.com/maps/api/geocode/xml?address=Leeds%20Train%20Station&sensor=false "
        Dim doc As XmlDocument = New XmlDocument()
        doc.Load(URLString)
        Dim nav As XPathNavigator = doc.CreateNavigator()
        Dim expr As XPathExpression, iterator As XPathNodeIterator
        expr = nav.Compile("/GeocodeResponse/result/address_component[long_name=""LS1 4""]/*")
        iterator = nav.Select(expr)
        For Each item As XPathNavigator In iterator
            'Get value for the selected expression
            Dim TheName As String = item.Name
            Dim TheValue As String = item.Value
        Next
    End Sub

Open in new window

David CIT Projects ManagerAuthor Commented:
Hi Stephan thank you very much we are almost there I have tried
 expr = nav.Compile("/GeocodeResponse/result/address_component[postal_code_prefix=""*""]/*") OR
expr = nav.Compile("/GeocodeResponse/result/address_component[postal_code_prefix]/*")

Because the URLString will be constantly changing. I need to take whatever value will be under postal code prefix?? I have tried the 2 wilcards above but they are not working
David CIT Projects ManagerAuthor Commented:
I dont know if that makes sense. The result has many <address_component> one of them will have a <type> that is 'postal_code_prefix' and in that component is where I want to take the long_name. This is because other long_names have other details. UNLESS there is a way I can change the Google query to return only the element with a type of postal_code_prefix
Asim NazirCommented:
Please try below code:
Private Function ProcessXml() As String
        Dim sParsedValue As [String] = String.Empty
        Dim sParsingValue As String = String.Empty
        Dim document As XmlDocument = New XmlDocument()

        sParsingValue = "/GeocodeResponse/result/address_component/type"
        document.Load("http://maps.googleapis.com/maps/api/geocode/xml?address=Leeds%20Train%20Station&sensor=false ")

        ' Create a navigator to query with XPath.
        Dim nav As XPathNavigator = document.CreateNavigator()

        Try
            Dim iterator As XPathNodeIterator = nav.[Select](sParsingValue)
            For Each item As XPathNavigator In iterator
                ' Get value for the selected expression
                sParsedValue = item.Value
                If (sParsedValue.Equals("postal_code_prefix")) Then
                    Exit For
                End If
            Next
        Catch
        End Try

        Return sParsedValue
    End Function
David CIT Projects ManagerAuthor Commented:
Thanks Asim! This works however instead of returning LS1 4 it returns postal_code_prefix Im sure its one little tweak to make it work
David CIT Projects ManagerAuthor Commented:
In my terms If (sParsedValue.Equals("postal_code_prefix")) Then when it is that. We need to find the value of <long_name>LS1 4</long_name> OR  <short_name>LS1 4</short_name> in that branch
Asim NazirCommented:
Private Function ProcessXml() As String
        Dim sParsedValue As [String] = String.Empty
        Dim sParsingValue As String = String.Empty
        Dim document As XmlDocument = New XmlDocument()

        sParsingValue = "/GeocodeResponse/result/address_component/type"
        document.Load("http://maps.googleapis.com/maps/api/geocode/xml?address=Leeds%20Train%20Station&sensor=false ")

        ' Create a navigator to query with XPath.
        Dim nav As XPathNavigator = document.CreateNavigator()

        Try
            Dim iterator As XPathNodeIterator = nav.[Select](sParsingValue)
            For Each item As XPathNavigator In iterator
                ' Get value for the selected expression
                sParsedValue = item.Value
                If (sParsedValue.Equals("postal_code_prefix")) Then
                    item.MoveToParent()
                    item.MoveToFirstChild()
                    sParsedValue = item.InnerXml

                    Exit For
                End If
            Next
        Catch
        End Try

        Return sParsedValue
    End Function

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
David CIT Projects ManagerAuthor Commented:
Thanks to Stephan and Asim. More points given to Asim as the full working solution was got from him. Wonderful Stuff!
StefanLambdaCommented:
Please find this one , It goes directly to the long_name being inside address_component having  a type="postal_code"

 
Private Sub DotIt()
        Const URLString As String = "http://maps.googleapis.com/maps/api/geocode/xml?address=Leeds%20Train%20Station&sensor=false"
        Dim doc As XmlDocument = New XmlDocument()
        doc.Load(URLString)
        Dim TheValueDir As String = doc.CreateNavigator().SelectSingleNode("//address_component[type=""postal_code""]/long_name").Value
    End Sub

Open in new window


or this one( to see several xpath)

 
Private Sub DotIt2()
        Const URLString As String = "http://maps.googleapis.com/maps/api/geocode/xml?address=Leeds%20Train%20Station&sensor=false "
        Dim doc As XmlDocument = New XmlDocument()
        doc.Load(URLString)
        Dim nav As XPathNavigator = doc.CreateNavigator()
        Dim expr As XPathExpression, iterator As XPathNodeIterator
        expr = nav.Compile("/GeocodeResponse/result/address_component[type=""postal_code""]/long_name")

        ' OR   expr = nav.Compile("//address_component[type=""postal_code""]/long_name")   
        ' OR   expr = nav.Compile("//address_component[type=""postal_code""]/*")     --> all nodes in address_component

        iterator = nav.Select(expr)
        For Each item As XPathNavigator In iterator
            'Get value for the selected expression
            Dim TheName As String = item.Name
            Dim TheValue As String = item.Value
        Next
    End Sub

Open in new window

David CIT Projects ManagerAuthor Commented:
Wow! Should have equally split points!
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
ASP.NET

From novice to tech pro — start learning today.