locked
XML Read Element Problem.

    Question

  • I am unable to retrieve the value (90.29) in "frbny:OBS_VALUE" tag. Below is my asp.net codes and also my XML file.

    Error Message- XMLException: Element 'frbny:OBS_VALUE' was not found. Line 2, position 2.

    PLEASE ASSIST ME ASAP!!! THANK YOU!!!

    ASP.NET Codes

    Dim
    reader As New XmlTextReader("C:\Documents and Settings\Lim Jian Da\My Documents\Visual Studio 2005\WebSites\WebSite12\SGD.xml")

    reader.Read()

    Dim asd As String = reader.ReadElementString("frbny:OBS_VALUE")

    lb_c.Text = asd

    ----------------------------------------------------------

    C:\Documents and Settings\Lim Jian Da\My Documents\Visual Studio 2005\WebSites\WebSite12\SGD.xml

    <?xml version="1.0" ?>

    - <UtilityData xsi:schemaLocation="http://www.SDMX.org/resources/SDMXML/schemas/v1_0/message http://www.sdmx.org/data/SDMXMessage.xsd http://www.newyorkfed.org/xml/schemas/FX/utility http://www.newyorkfed.org/xml/schemas/FX_Utility.xsd" xmlns:generic="http://www.SDMX.org/resources/SDMXML/schemas/v1_0/generic" xmlns="http://www.SDMX.org/resources/SDMXML/schemas/v1_0/message" xmlns:utility="http://www.SDMX.org/resources/SDMXML/schemas/v1_0/utility" xmlns:query="http://www.SDMX.org/resources/SDMXML/schemas/v1_0/query" xmlns:structure="http://www.SDMX.org/resources/SDMXML/schemas/v1_0/structure" xmlns:common="http://www.SDMX.org/resources/SDMXML/schemas/v1_0/common" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:compact="http://www.SDMX.org/resources/SDMXML/schemas/v1_0/compact" xmlns:frbny="http://www.newyorkfed.org/xml/schemas/FX/utility" xmlns:cross="http://www.SDMX.org/resources/SDMXML/schemas/v1_0/cross">
    - <Header>
      <ID>FX12JP</ID>
      <Test>false</Test>
      <Name xml:lang="en">Foreign Exchange Japan Yen Noon Rates</Name>
      <Prepared>2009-01-18</Prepared>
    - <Sender id="FRBNY">
      <Name xml:lang="en">Federal Reserve Bank of New York</Name>
    - <Contact>
      <Name xml:lang="en">Public Information Web Team</Name>
      <Email>ny.piwebteam@ny.frb.org</Email>
      </Contact>
      </Sender>
      <ReportingBegin>1993-10-05</ReportingBegin>
      </Header>
    - <frbny:DataSet>
    - <frbny:Series AVAILABILITY="A" DECIMALS="2" UNIT_MULT="0" TIME_FORMAT="P1D" UNIT="JPY" FX_METHOD="12" DISCLAIMER="12" AUTHORITY="12">
    - <frbny:Key>
      <frbny:FREQ>D</frbny:FREQ>
      <frbny:CURR>USD</frbny:CURR>
      <frbny:FX_TIME>12</frbny:FX_TIME>
      <frbny:FX_TYPE>S</frbny:FX_TYPE>
      </frbny:Key>
    - <frbny:Obs OBS_STATUS="A" OBS_CONF="F">
      <frbny:TIME_PERIOD>2009-01-16</frbny:TIME_PERIOD>
      <frbny:OBS_VALUE>90.29</frbny:OBS_VALUE>
      </frbny:Obs>
      </frbny:Series>
      </frbny:DataSet>
      </UtilityData>

    Tsuki O Miru Tabi Omoidaze
    Monday, January 19, 2009 7:01 AM

Answers

  • One problem you might be having is that your xml doc contains namespaces... because of this you will need to create and supply that namespace through an XmlNamespaceManger object that you can then pass into the SelectNodes or SelectSingleNoge methods.  Below is a code example that I used when parsing a xml doc from reporting services.

    XmlDocument doc = new XmlDocument();  
    doc.Load(new XmlTextReader(new StreamReader(this.newStream)));  
     
    XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);  
    nsmgr.AddNamespace("h""http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices");  
    XmlNodeList reportParams = doc.SelectNodes("//h:Parameters/h:ReportParameter",nsmgr); 


    The key is to define an alias for the namespace with the same url as in the document and then use that alias when referencing nodes.
    Tuesday, January 20, 2009 10:35 PM

All replies

  • Insteed of Using XMLReader ..you can use XPath or XDocument.

    You can also use LINQ to XML to parse the data.
    Monday, January 19, 2009 8:18 AM
  •  I appreciate if u can give me all the codes that is relevant, so that i can put into my .aspx page load. i am doing asp.net coding... I need he asp.net code to retrieve the value in tag of  .xml file.
    Tsuki O Miru Tabi Omoidaze
    Monday, January 19, 2009 8:33 AM
  •  One alternative would be for you to learn how to do these things on your own instead of asking others to do them for you.
    John Saunders | Use File->New Project to create Web Service Projects
    Monday, January 19, 2009 3:27 PM
    Moderator
  • I have been trying like crazy for many days!! my deadline is coming!!

    i did try below are one whole chunk of codes on my page load which i tried and tired but still can't work. putting in new codes commenting old codes that can't work.. but still can't work... please help me!!

    @John: very disappointed with yur reply.. Please help me up with my codes.. i already give u all my information.. i did my best already.

     

    'Session.Timeout [=nMinutes]

     

    'Dim hws As New org.newyorkfed.www.FXWSService

     

    'Dim zz As org.frb.ny.it.NoonExchangeRates.FC = New org.frb.ny.it.NoonExchangeRates.FC()

     

    'hws.getAllLatestNoonRates()

     

    'hws.getLatestNoonRate("SGD")

     

    'hws.getAllLatestNoonRates()

     

    'hws.getAllNoonRates(datez)

     

    'TextBox1.Text = hws.getAllLatestNoonRates

     

    'SGDXML = hws.getLatestNoonRate("SGD")

     

    'Dim asd As String

     

    'Dim RootElement As XmlElement = New XmlElement



     

    'Dim File As System.IO.File

     

    'Dim oWrite As System.IO.StreamWriter

     

    'oWrite = File.CreateText("C:\Documents and Settings\Lim Jian Da\My Documents\Visual Studio 2005\WebSites\WebSite12\SGD.xml")





     

    'oWrite.WriteLine(SGDXML)

     

    'oWrite.Close()



     

    'Dim doc As XmlDocument = New XmlDocument

     

    'doc.Load("C:\Documents and Settings\Lim Jian Da\My Documents\Visual Studio 2005\WebSites\WebSite12\SGD.xml")











     

    'Dim zzzNodeList As XmlNodeList

     

    'Dim doc As XmlDocument = New XmlDocument

     

    'Dim RootElement As XmlElement

     

    'doc.Load("C:\Documents and Settings\Lim Jian Da\My Documents\Visual Studio 2005\WebSites\WebSite12\SGD.xml")

     

    ''zzzNodeList = RootElement.ChildNodes

     

    ''For Each zzz As XmlElement In zzzNodeList

     

    'asd = zzz.GetAttribute("frbny:OBS_VALUE")

     

    ''Next

     

    'lb_c.Text = asd

     

    'Dim oRead As System.Xml.XmlReader = ("C:\Documents and Settings\Lim Jian Da\My Documents\Visual Studio 2005\WebSites\WebSite12\SGD.xml")

     

    'Dim xmlDoc = New XmlDocument

     

    'xmlDoc.Load(oRead)

     

    'oRead = oFile.ReadAllText

     

    'Dim strType As String = "Oracle"

     

    'Dim reader As New XmlTextReader("C:\Documents and Settings\Lim Jian Da\My Documents\Visual Studio 2005\WebSites\WebSite12\SGD.xml")

     

    'reader.MoveToContent()

     

    'reader.Read()

     

    'Dim dsa As New XPath

     

    'Dim asd As String = reader.ReadElementString("frbny:OBS_VALUE")

     

    'strType = reader.GetAttribute("frbny:OBS_VALUE")

     

    'lb_c.Text = asd





     

    'Dim xmlDoc = New ActiveXObject("Microsoft.XMLDOM")

     

    'xmlDoc.async = "false"

     

    'xmlDoc.loadXML(TextBox2.Text)









     

    'TextBox3.Text = hws.getAllLatestNoonRates()

     

    'TextBox4.Text = hws.getAllNoonRates(datez)

     

    'TextBox6.Text = hws.GetLifetimeService

     

    'TextBox4.Text = hws.getNoonRates("SGD", datez, datez)

     

    'TextBox5.Text = hws.getAllNoonRatesAsync(datez)

     

    'TextBox5.Text = hws.BegingetAllLatestNoonRates(callback as systen.asynccallback)

     

    'string getNoonRates ( string currency_code, date date1, date date2 )

     

    'time.session()

     

    'fc.BegingetAllLatestNoonRates()

     

    'Dim asd As String = hws.getLatestNoonRate("JPY")

     

    'Dim readers As System.Xml.XmlReader = hws.getLatestNoonRate("JPY")

     

    'TextBox5.Text = zz.getAllLatestNoonRates()

     

    'Dim readers As System.Xml.XmlReader = XmlReader.Create("C:\Documents and Settings\Lim Jian Da\My Documents\Visual Studio 2005\WebSites\WebSite12\YEN2.xml")

     

    'Dim m_xmlr As XmlTextReader = New XmlTextReader("C:\Documents and Settings\Lim Jian Da\My Documents\Visual Studio 2005\WebSites\WebSite12\YEN2.xml")

     

    'Dim strReader As New StringReader(hws.getLatestNoonRate("JPY"))

     

    'Dim m_xmlr As XmlTextReader = New XmlTextReader(strReader)

     

    'm_xmlr.WhitespaceHandling = WhitespaceHandling.None

     

    'm_xmlr.Read()

     

    'Dim asd As String = m_xmlr.ReadElementString("Email")



     

    'lb_c.Text = asd



     

    'Dim ds As New Data.DataSet



     

    'Try

     

    ' ds.ReadXml("C:\Documents and Settings\Lim Jian Da\My Documents\Visual Studio 2005\WebSites\WebSite12\SGD.xml")

     

    'Catch ex As Exception

     

    ' MessageBox.Show(ex.Message)

     

    ' Exit Sub

     

    'End Try

     

    'Dim dr() As DataRow

     

    'Dim dr1 As DataRow

     

    'dr = ds.Tables(0).Select("frbny:OBS_VALUE")

     

    'lb_c.Text = Convert.ToString(dr.ToString)

     

    'For Each dr1 In dr

     

    ' lb_c.Text = dr1

     

    ' your result stored here

     

    'Next

     


    Tsuki O Miru Tabi Omoidaze
    Monday, January 19, 2009 3:34 PM
  • Does nobody else in your company understand XML? You're really at the point right now where you've got the data and just need to learn enough about XML to go process it. Either that, or you need someone to do your job for you, for free.

    You were on the right track by loading the entire thing into an XmlDocument. Once you've got it in an XmlDocument, you can learn the structure of the document by simply looping through the collections of ChildNodes. Try looping through doc.DocumentElement.ChildNodes. For each child node then, loop through all of its ChildNodes. You will learn the structure of the document that way.


    John Saunders | Use File->New Project to create Web Service Projects
    Monday, January 19, 2009 4:45 PM
    Moderator
  •  do i need to use?

    .getAttribute

    or getElementString()??

    I really hope u can just write out the segment of code for me, accoding to the information I provided above.
    If you are afriad that i don't understand the code you gave me, maybe u might want to explain it line by line.
    Hey John Please help me... I am just a Student... Thank you!
    Tsuki O Miru Tabi Omoidaze
    Monday, January 19, 2009 4:53 PM
  • Student, here is some homework. Look at the properties of the XmlNode class. In particular, look at those properties that navigate to other XmlNode instances or which are collections of other XmlNode instances. See http://msdn.microsoft.com/en-us/library/system.xml.xmlnode_members.aspx.

    Hint: as I said above, write some code to display ChildNodes. You've already got most of the code you need, commented out.
    John Saunders | Use File->New Project to create Web Service Projects
    Monday, January 19, 2009 5:25 PM
    Moderator
  • One problem you might be having is that your xml doc contains namespaces... because of this you will need to create and supply that namespace through an XmlNamespaceManger object that you can then pass into the SelectNodes or SelectSingleNoge methods.  Below is a code example that I used when parsing a xml doc from reporting services.

    XmlDocument doc = new XmlDocument();  
    doc.Load(new XmlTextReader(new StreamReader(this.newStream)));  
     
    XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);  
    nsmgr.AddNamespace("h""http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices");  
    XmlNodeList reportParams = doc.SelectNodes("//h:Parameters/h:ReportParameter",nsmgr); 


    The key is to define an alias for the namespace with the same url as in the document and then use that alias when referencing nodes.
    Tuesday, January 20, 2009 10:35 PM
  •  ok let me explain to u guys.... I am doing a foreign curency exchange whereby i need the exchange rates from online web service...
    this is the website http://www.ny.frb.org/markets/pilotfx.html and u will find out that the Web Service Definition (WSDL):
    http://www.newyorkfed.org/markets/fxrates/WebService/v1_0/FXWS.wsdl 

    I am able to add reference and retrieve it but it is all xml texts..(which is shown above). therefore,  I am using the below codes on my page load so that whenever i load my aspx.. it will create and overwrite the xml files.. which means i will get the latest exchange rate...

     


     

    Dim hws As New org.newyorkfed.www.FXWSService

     

    SGDXML = hws.getLatestNoonRate("SGD")



     

    Dim oWrite As System.IO.StreamWriter

    oWrite = File.CreateText("C:\Documents and Settings\Lim Jian Da\My Documents\Visual Studio 2005\WebSites\WebSite12\SGD.xml")

    oWrite.WriteLine(SGDXML)

    oWrite.Close()

    @JOHN: you say i am on the right track by loading the xml but after that i really dunno what to do... please just help me with the codes.... u just keep talking but no codes provided from u at all... i have read  http://msdn.microsoft.com/en-us/library/system.xml.xmlnode_members.aspx i still dunno understand and dunno how to apply it..



    'Dim doc As XmlDocument = New XmlDocument

    'doc.Load("C:\Documents and Settings\Lim Jian Da\My Documents\Visual Studio 2005\WebSites\WebSite12\SGD.xml")

     

    'asd = zzz.GetAttribute("frbny:OBS_VALUE")

     

    'lb_c.Text = asd


    OR


    Gave me an error, i know i need XPATH but i dunno what is XPATH. izzt a xml code??? for you guys info, i cannot edit my xml file.. my xml file is loaded from web service...

    Dim doc As XmlDocument = New XmlDocument

    doc.Load("C:\Documents and Settings\Lim Jian Da\My Documents\Visual Studio 2005\WebSites\WebSite12\SGD.xml")

    Dim node As XmlNode = doc.SelectSingleNode("frbny:OBS_VALUE") <--- i know putting frbny... is wrong...

    Dim asd As String = node.Value

    lb_c.Text = asd





    sorry ealders I don't understand your code... xmlnamespacemanager??? i got curly lines putting this code...

    and for doc.load should my code be 

    doc.Load("C:\Documents and Settings\Lim Jian Da\My Documents\Visual Studio 2005\WebSites\WebSite12\SGD.xml")

    ??? so after that what codes shld i put in??


    can someone KINDLY just write me the codes PLEASE!!!! I just need to retrieve the value of the tag frbny:OBS_VALUE which is 90.29 . this will be my last post, if there is no relevant help given...


    Tsuki O Miru Tabi Omoidaze
    Thursday, January 22, 2009 3:31 PM
  • There's an old saying: "Give a man a fish, and you'll feed him for a day; teach a man to fish, and you'll feed him for a lifetime". Here are some "how to fish using XML" articles:

    Frankly, this stuff is fairly simple (with the possible exception of namespaces). You might want to see if you can find a simple book on XML. Unfortunately, I don't know of one offhand.


    John Saunders | Use File->New Project to create Web Service Projects
    Thursday, January 22, 2009 5:16 PM
    Moderator
  • I got my code already my teacher gave me the code and it works.. below is the codes..  my deadline is a few days later and you guys drag with me for so long..

    There is an even old saying: "Saving a drowned man, you will save a life; teaching him how to swim, when he is drowning will cost a life".

    I understand u want me to learn for myself, but mine is urgent case! hey john and ealder... thx anyway.. even though u 2 nvr helped me with the codes at all... take care!

     

    Dim SGDx As Double

     

    Dim FILE_NAME As String = "C:\Documents and Settings\Lim Jian Da\My Documents\Visual Studio 2005\WebSites\jianda2\XMLFolder\SGD.xml"

     

    Dim TextLine As String

     

    Dim startingpt As Integer

     

    Dim endingpt As Integer

     

    If System.IO.File.Exists(FILE_NAME) = True Then

     

    Dim objReader As New System.IO.StreamReader(FILE_NAME)

    Do While objReader.Peek() <> -1

    TextLine = objReader.ReadLine()

    If TextLine.EndsWith("</frbny:DataSet>") Then

     

    startingpt = TextLine.IndexOf("<frbny:OBS_VALUE>") + 17

    endingpt = TextLine.IndexOf("</frbny:OBS_VALUE>")

    SGDx = TextLine.Substring(startingpt, endingpt - startingpt)

    End If

     

    Loop

     

    objReader.Close()

    End If


    Tsuki O Miru Tabi Omoidaze
    Friday, January 23, 2009 10:17 AM
  • Great. Now, can you tell me what you've learned?

    If you haven't learned anything, yet you pass the class, then your employers will later realize that you don't know what you're doing. In this case, you will wish you had found a way to learn it instead of looking for ways to get someone to give you the answer. If you had been employed, and a supervisor had been looking over your shoulder and saw that this is the way you approach problem solving, do you think he would have been pleased?

    You didn't "learn to fish (or swim)" before now. I suggest you take the time to learn for next time you need a fish.

    BTW, I just looked at the code your "teacher" gave you. He must really hate you. That code is very wrong. You must never treat XML like it's just text. In particular, the prefix (frbny) does not matter. It could be any string at all, and the meaning of the document would be identical. If you are depending on the prefix staying the same, then your code is dangerously incorrect.


    John Saunders | Use File->New Project to create Web Service Projects
    Friday, January 23, 2009 11:40 PM
    Moderator
  • oh well.. i got can get the value i wanted... i am very greatfull to my teacher... i understand his codes..
    Tsuki O Miru Tabi Omoidaze
    • Proposed as answer by Andrew Salmon Friday, February 13, 2009 12:07 AM
    Saturday, January 24, 2009 3:02 AM
  • You may understand it, but the code is incorrect. As soon as the web service changes the prefix in its XML reply, your code will break. If an attribute is added to the OBS_VALUE element, your code will break. If the newline or space characters change, your code will break.

    If you show this kind of code to an employer, you will have trouble being hired. There are many, many classes in the System.Xml.* namespaces. If the right way to deal with XML was the way your "teacher" showed you, then none of them would have been written.

    End of lecture. Good luck.


    John Saunders | Use File->New Project to create Web Service Projects
    Saturday, January 24, 2009 7:47 PM
    Moderator
  • I thought that I would offer a little assistance after comming accross this post whilst trying to find details on the FXWS web service.  I had a problem initialy with the namespace but found that ealders code reminded me that I should add the namespace to the Select method - thanks ealders.

    I have just added the following code to my web site (Still needs a little more exception handling etc.) but it works very well.  John is correct when he says that your code relies on the XML having the same markup each time you call the service.

          // Get Exchange rate for GBP Pounds to US Dollar.  
          // ==============================================  
     
          Decimal GBP = 0;  
     
          // Define the Exchange Rates Service  
     
          NewYorkForeignExchangeRates.FXWSService _exchangeRateService = new NewYorkForeignExchangeRates.FXWSService();  
     
     
          // Get the XML data as a string  
     
          String _xmlData = "";  
          try 
            {  
            _xmlData = _exchangeRateService.getLatestNoonRate("GBP");  
            }  
          catch (Exception)  
            {  
            }  
     
     
          if (_xmlData != null)  
            {  
            XmlDocument _ratesDoc = new XmlDocument();  
            _ratesDoc.LoadXml(_xmlData);  
     
            XmlNamespaceManager nsmgr = new XmlNamespaceManager(_ratesDoc.NameTable);  
            nsmgr.AddNamespace("frbny""http://www.newyorkfed.org/xml/schemas/FX/utility");  
     
            XmlNode _rateNode = _ratesDoc.SelectSingleNode("//frbny:OBS_VALUE", nsmgr);  
     
            if (_rateNode != null)  
              GBP = Convert.ToDecimal(_rateNode.InnerText);  
            }  

     

    I hope you find this helpful

    • Proposed as answer by Andrew Salmon Friday, February 13, 2009 12:41 AM
    Friday, February 13, 2009 12:25 AM