I'm new to VB.net and I'm having trouble figuring out how to load the XML data into a DropDownList from a HttpWebRequest. The Data I want to load into the DropDownList is Merchant + Price. Down below is my code:
Dim s As HttpWebRequest
s = HttpWebRequest.Create("myURL")
s.Method = "GET"
Dim postresponse As HttpWebResponse
postresponse = DirectCast(s.GetResponse, HttpWebResponse)
Dim postreqreader As New Stream(postresponse.GetResponseStream())
Dim returnData As String = postreqreader.ReadToEnd
postresponse.Close()
The XML response I'm getting back from returnData is:
<xml version="1.0" encoding="UTF-8" ?>
<Response>
<ID>123</ID>
<Items>
<Item>
<Isbn>123456789</Isbn>
<Offers>
<Offer>
<Isbn>123456789</Isbn>
<Merchant>Vendor1</Merchant>
<Price>3.00</Price>
<Shipping>8.00<Shipping>
</Offer>
<Offer>
<Isbn>123456789</Isbn>
<Merchant>Verndor2</Merchant>
<Price>3.00</Price>
<Shipping>8.00<Shipping>
</Offer>
</Offers>
</Item>
</Items>
</Response>
First ensure you close your Shipping tags.
Try something like this:
Dim ds As New DataSet()
ds.ReadXml(new XmlTextReader(new StringReader(returnData )))
ds.Tables("Offer").Columns.Add("MerchantPrice", GetType(String), "Merchant + ' - ' + Price")
Dim dv As DataView = ds.Tables("Offer").DefaultView
dv.Sort = "Merchant"
ddlMerchant.DataTextField = "MerchantPrice"
ddlMerchant.DataValueField = "Isbn"
ddlMerchant.DataSource = dv
ddlMerchant.DataBind()
first convert the xml in to dataset using this code
DataSet ds;
StringReader reader = new StringReader(string);
ds.ReadXml(reader);
and then bind it to DropDownList
Related
I want to fill my dropdownlist with all the payment methods, i should find the payment methods in an xml file that i have. this should be the xml code for the methods:
Dim xml As String
xml = "<?xml version=""1.0"" encoding=""UTF-8""?>"
xml &= "<gateways ua=""example-php-1.1"">"
xml &= "<merchant>"
xml &= " <account>123456</account>"
xml &= " <site_id>789</site_id>"
xml &= " <site_secure_code>112233</site_secure_code>"
xml &= "</merchant>"
xml &= "<customer>"
xml &= " <country>NL</country>"
xml &= " <locale>nl_NL</locale>"
xml &= "</customer>"
xml &= " </gateways>"
Dim apiURl As String
apiURl = "https://testapi.multisafepay.com/ewx/"
Dim httpWebRequest As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create(apiURl)
httpWebRequest.Method = "POST"
httpWebRequest.ContentLength = System.Text.Encoding.UTF8.GetByteCount(xml)
httpWebRequest.ContentType = "application/x-www-form-urlencoded"
Dim streamWriter = New System.IO.StreamWriter(httpWebRequest.GetRequestStream())
streamWriter.Write(xml)
streamWriter.Close()
Dim httpWebResponse As System.Net.HttpWebResponse = httpWebRequest.GetResponse()
Dim streamReader = New System.IO.StreamReader(httpWebResponse.GetResponseStream())
Dim stringResult = streamReader.ReadToEnd()
Dim xmlstring As String = stringResult
Dim xd As System.Xml.XmlDocument = New System.Xml.XmlDocument()
xd.LoadXml(xmlstring)
the stringResult gives this Value:
<?xml version="1.0" encoding="UTF-8"?>
<gateways result="ok">
<gateways>
<gateway>
<id>IDEAL</id>
<description>iDEAL</description>
</gateway>
<gateway>
<id> MASTERCARD</id>
<description>Visa via Multipay</description>
</gateway>
<gateway>
<id> BANKTRANS</id>
<description> Bank Transfer</description>
</gateway>
<gateway>
<id> VISA</id>
<description> Visa CreditCards</description>
</gateway>
</gateways>
</gateways>
i need to get the value between the <id></id> tags in my ddlMethod how can i do this?
You can use SelectNodes() method to get specific nodes from XmlDocument passing suitable XPath string as the method parameter. Since SelectNodes() returns collection of XmlNode, you also need to specify which property of XmlNode to be displayed in the dropdown list control. In this case, I assume you want to display the text between <id> tags so we use InnerText property :
Dim xd As System.Xml.XmlDocument = New System.Xml.XmlDocument()
xd.LoadXml(xmlstring)
'set data source of dropdown to all <id> elements from XML'
ddlMethod.DataSource = xd.SelectNodes("//id")
ddlMethod.DataTextField = "InnerText"
ddlMethod.DataValueField = "InnerText"
ddlMethod.DataBind()
Only if available in the .NET framework version you're using, I'd suggest to switch to XDocument which is more modern XML library in .NET compared to the older XmlDocument. In various situations XDocument is more friendly to use than XmlDocument. Example using XDocument and LINQ style :
Dim xd As XDocument = XDocument.Parse(xmlstring)
'set data soutce of dropdown to *content* of all <id> elements from XML'
ddlMethod.DataSource = xd.Descendants("id").Select(Function(x) x.Value)
ddlMethod.DataBind()
i came up with this and it works for me:
Dim bytTeller As Byte
For bytTeller = 0 To xd.GetElementsByTagName("gateway").Count - 1
Dim root As XmlNode = xd.GetElementsByTagName("gateway").Item(bytTeller)
ddlMethod.Items.Add(root.ChildNodes(0).InnerText)
Next
Okay I have a custom XML string that is provided so unable to modify structure it is a key value pair as seen here
<?xml version='1.0' encoding='utf-8'?>
<ContentStack ID='13' Type='11'>
<ContentElement1 ID='11' Type='IMAGE'>
<Key AttributeName='Name' AttributeValue='SOMENAME'></Key>
<Key AttributeName='SRC' AttributeValue='SOMEFILE.jpg'></Key>
<Key AttributeName='ALT' AttributeValue='SOMEALT'></Key>
<Key AttributeName='Class' AttributeValue='SOMECLASS'></Key>
</ContentElement1>
</ContentStack>
I want to be able to grab the attribute value and assign them to a variable so I end up with something like this.
Dim thsValueOne AS String = "SOMENAME"
Dim thsValueTwo AS String = "SOMEFILE.jpg"
Dim thsValueThree AS String = "SOMEALT"
Dim thsValueFour AS String = "SOMECLASS"
I have tried doing similar to this with no luck
Dim xDoc As XDocument = XDocument.Parse(" MY XML STING IN HERE ")
thsValueOne = xDoc.Descendants("Key.AttributeValue").Skip(0).Take(1).ToString
I'm thinking I'm no where near close.
Ok was able to get this figured out base on XML in question answer was simple
Dim xDoc As XDocument = XDocument.Parse(thsXmlContent)
thsValueOne = xDoc.Root.Descendants.<Key>(0).#AttributeValue
thsValueTwo = xDoc.Root.Descendants.<Key>(1).#AttributeValue
thsValueThree = xDoc.Root.Descendants.<Key>(2).#AttributeValue
thsValueFour = xDoc.Root.Descendants.<Key>(3).#AttributeValue
You can try out any of the below workarounds, in order to understand the concept.
As you are using VB.NET you can use XML literals:
Private Sub test1()
Dim xFrag = <?xml version='1.0' encoding='utf-8'?>
<ContentStack ID='13' Type='11'>
<ContentElement1 ID='11' Type='IMAGE'>
<Key AttributeName='Name' AttributeValue='SOMENAME'></Key>
<Key AttributeName='SRC' AttributeValue='SOMEFILE.jpg'></Key>
<Key AttributeName='ALT' AttributeValue='SOMEALT'></Key>
<Key AttributeName='Class' AttributeValue='SOMECLASS'></Key>
</ContentElement1>
</ContentStack>
Dim query = xFrag...<Key>, pos& = 0
For Each ele As XElement In query
pos += 1
MsgBox(String.Format("Test1:Key({0}):AttributeName='{1}' AttributeValue='{2}'", pos.ToString, ele.#AttributeName, ele.#AttributeValue))
Next ele
End Sub
Or otherwise use the Parse method.
Private Sub test2()
Dim xStr = "<?xml version='1.0' encoding='utf-8'?><ContentStack ID='13' Type='11'><ContentElement1 ID='11' Type='IMAGE'><Key AttributeName='Name' AttributeValue='SOMENAME'></Key><Key AttributeName='SRC' AttributeValue='SOMEFILE.jpg'></Key><Key AttributeName='ALT' AttributeValue='SOMEALT'></Key><Key AttributeName='Class' AttributeValue='SOMECLASS'></Key></ContentElement1></ContentStack>"
Dim xFrag = XDocument.Parse(xStr)
Dim query = xFrag...<Key>, pos& = 0
For Each ele As XElement In query
pos += 1
MsgBox(String.Format("Test2:Key({0}):AttributeName='{1}' AttributeValue='{2}'", pos.ToString, ele.#AttributeName, ele.#AttributeValue))
Next ele
End Sub
Hope this helps...
I have an Editable GridView control that functions off of an XML file. The GridView contains an empty-data-template given that the xml file contains no data on page load. The empty-data-template consist of two textbox controls and a link-button for placing data into the xml file, and thus should cause the Gridview to display. My problem is that when I click the link button, I get an Object-reference related error in response to this line: Dim oDr As DataRow = oDs.Tables("po").NewRow ...the full event handler, I provided below:
The code behind:
Public Sub writeStartpoNum()
Dim startpoNumID As String = DirectCast(gvPurchaseOrderNum.Controls(0).Controls(0).FindControl("txtStartpoNumID"), TextBox).Text
Dim startpoNum As String = DirectCast(gvPurchaseOrderNum.Controls(0).Controls(0).FindControl("txtStartpoNum"), TextBox).Text
Dim oDs As New DataSet()
Dim xmlPath As String = MapPath("~/xml/newShipment.xml")
If Not System.IO.File.Exists(xmlPath) Then
oDs.DataSetName = "newShipmentNotification"
oDs.Tables.Add("pos")
oDs.Tables("pos").Columns.Add("pos_Id")
oDs.Tables("pos").Columns("pos_Id").ColumnMapping = MappingType.Hidden
oDs.Tables.Add("po")
oDs.Tables("po").Columns.Add("ponumberID")
oDs.Tables("po").Columns.Add("pos_Id")
oDs.Tables("po").Columns("pos_Id").ColumnMapping = MappingType.Hidden
oDs.Tables("po").Columns.Add("ponumber")
Dim pos_po As DataRelation = oDs.Relations.Add("pos_po", oDs.Tables("pos").Columns("pos_Id"), _
oDs.Tables("po").Columns("pos_Id"))
pos_po.Nested = True
Dim oDrs As DataRow = oDs.Tables("pos").NewRow
oDrs("pos_Id") = 0
oDs.Tables("pos").Rows.Add(oDrs)
Else
oDs.ReadXml(Server.MapPath("~/xml/newShipment.xml"))
End If
Dim oDr As DataRow = oDs.Tables("po").NewRow
oDr("ponumberID") = startpoNumID
oDr("ponumber") = startpoNum
oDr("pos_Id") = 0
oDs.Tables("po").Rows.Add(oDr)
oDs.WriteXml(Server.MapPath("~/xml/newShipment.xml"))
gvPurchaseOrderNum.DataSource = oDs.Tables("po")
gvPurchaseOrderNum.DataBind()
End Sub
...this is the design for the empty-data-template in the Gridview:
<emptydatatemplate>
<b>Enter Purchase Order Number:</b> <br />
<asp:TextBox ID="txtStartpoNumID" runat="server"></asp:TextBox>
<asp:TextBox ID="txtStartpoNum" runat="server"></asp:TextBox><br />
<asp:LinkButton ID="lnkpro" runat="server" OnClick="writeStartpoNum" Text="Add Purchase order Number"></asp:LinkButton>
<br /><br />
</emptydatatemplate>
...this is how the xml reflects on page load as a results of a function that clears the xml file of any data if the xml file contains data on page load.
<?xml version="1.0" standalone="yes"?>
<newShipmentNotification>
<pos />
</newShipmentNotification>
...As I mentioned, when debugged - the issue stems from the following line
Dim oDr As DataRow = oDs.Tables("po").NewRow
The xml is build out, via the conditional statement. What I cannot figure is why the dataset variable (oDs), even though it reflects the pos table when viewed in debug mode, still generates an object-reference related error. Please provide some direction as to what I may be doing wrong here or if there is something I'm missing. Thanks
The issue is when you have the xml file without 'po' node. You can move the node to a new
method like:
Private Function CreatePOSDataset() As DataSet
Dim oDs As New DataSet()
oDs.DataSetName = "newshipmentnotification"
oDs.Tables.Add("pos")
oDs.Tables("pos").Columns.Add("pos_Id")
oDs.Tables("pos").Columns("pos_Id").ColumnMapping = MappingType.Hidden
oDs.Tables.Add("po")
oDs.Tables("po").Columns.Add("ponumberID")
oDs.Tables("po").Columns.Add("pos_Id")
oDs.Tables("po").Columns("pos_Id").ColumnMapping = MappingType.Hidden
oDs.Tables("po").Columns.Add("ponumber")
Dim pos_po As DataRelation = oDs.Relations.Add("pos_po", oDs.Tables("pos").Columns("pos_Id"), _
oDs.Tables("po").Columns("pos_Id"))
pos_po.Nested = True
Dim oDrs As DataRow = oDs.Tables("pos").NewRow
oDrs("pos_Id") = 0
oDs.Tables("pos").Rows.Add(oDrs)
CreatePOSDataset = oDs
End Function
And call the method when 'po' node does not exist:
Public Sub writeStartpoNum(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim startpoNumID As String = DirectCast(gvPurchaseOrderNum.Controls(0).Controls(0).FindControl("txtStartpoNumID"), TextBox).Text
Dim startpoNum As String = DirectCast(gvPurchaseOrderNum.Controls(0).Controls(0).FindControl("txtStartpoNum"), TextBox).Text
Dim oDs As New DataSet()
Dim xmlPath As String = MapPath("~/xml/newshipmentnotification.xml")
If Not System.IO.File.Exists(xmlPath) Then
oDs = CreatePOSDataset()
Else
oDs.ReadXml(Server.MapPath("~/xml/newshipmentnotification.xml"))
If oDs.Tables("po") Is Nothing Then
oDs = CreatePOSDataset()
End If
End If
Dim oDr As DataRow = oDs.Tables("po").NewRow
oDr("ponumberID") = startpoNumID
oDr("ponumber") = startpoNum
oDr("pos_Id") = 0
oDs.Tables("po").Rows.Add(oDr)
oDs.WriteXml(Server.MapPath("~/xml/newshipmentnotification.xml"))
gvPurchaseOrderNum.DataSource = oDs.Tables("po")
gvPurchaseOrderNum.DataBind()
End Sub
I have this XML content:
<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Option1>false</Option1>
<Option2>http://www.google.com</Option2>
<Option3>false</Option3>
<Option4>false</Option4>
</configuration>
I trying to use code bellow to read this xml but Dataset.tables.count always return 0.
Dim dtConfig As New DataSet
Dim sArqXml as String = "asd.xml"
Dim xmlRoot As New XmlRootAttribute
xmlRoot.ElementName = "configuration"
xmlRoot.IsNullable = True
Dim xmlSer As XmlSerializer = New XmlSerializer(dtConfig.GetType, xmlRoot)
Dim fs As FileStream = New FileStream(sArqXml, FileMode.Open)
dtConfig = CType(xmlSer.Deserialize(fs), DataSet)
fs.Close()
How can I read this XML? The solution can be in c#.
To load a xml file into a dataset.
Imports System.Xml
Dim ds As New DataSet
ds.ReadXml("path_to_your_xml_file")
and I think it should be ds.Table(0).Rows.Count in your case
I am posting to a website to get data back. The site returns it as an xml. I am able to get the data into a string. But what i really want to do is to have each item in the xml in a different string field.
Sub lookup(ByVal Source As Object, ByVal e As EventArgs)
Dim wData As String
wData = WRequest("http://PostToThisSite.com", "POST","str=31&Password=pn&UserID=Q&Postcode="+txtPcode.Text)
Response.Write(wData)
End Sub
Function WRequest(URL As String, method As String, POSTdata As String) As String
Dim responseData As String = ""
Try
Dim hwrequest As Net.HttpWebRequest = Net.Webrequest.Create(URL)
hwrequest.Accept = "*/*"
hwrequest.AllowAutoRedirect = true
hwrequest.UserAgent = "http_requester/0.1"
hwrequest.Timeout = 60000
hwrequest.Method = method
If hwrequest.Method = "POST" Then
hwrequest.ContentType = "application/x-www-form-urlencoded"
Dim encoding As New Text.ASCIIEncoding() 'Use UTF8Encoding for XML requests
Dim postByteArray() As Byte = encoding.GetBytes(POSTdata)
hwrequest.ContentLength = postByteArray.Length
Dim postStream As IO.Stream = hwrequest.GetRequestStream()
postStream.Write(postByteArray, 0, postByteArray.Length)
postStream.Close()
End If
Dim hwresponse As Net.HttpWebResponse = hwrequest.GetResponse()
If hwresponse.StatusCode = Net.HttpStatusCode.OK Then
Dim responseStream As IO.StreamReader = _
New IO.StreamReader(hwresponse.GetResponseStream())
responseData = responseStream.ReadToEnd()
End If
hwresponse.Close()
Catch e As Exception
responseData = "An error occurred: " & e.Message
End Try
Return responseData
End Function
The above code works and writes out a line...
Some Road City LU1 5QG
The Xml being returned is ..
<Address xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://site.co.uk/">
<strOrganisation />
<strProperty />
<strStreet>Some Road</strStreet>
<strLocality />
<strTown>City</strTown>
<strCounty />
<strPostcode>LU1 5QG</strPostcode>
<strDPS />
I want to be able to split these fields and set them to different text boxes on the page...help?
Load the xml string into an XmlDocument and extract the values with XPath:
Dim doc = new XmlDocument()
doc.LoadXml(yourXmlString)
Dim nsm = new XmlNamespaceManager(doc.NameTable)
nsm.AddNamespace("a", "http://site.co.uk/")
txtStreet.Text = doc.SelectSingleNode("/a:Address/a:strStreet", nsm).InnerText
Here's a working snippet:
Dim doc = New XmlDocument()
doc.LoadXml("<Address xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://site.co.uk/""><strOrganisation /> <strProperty /> <strStreet>Some Road</strStreet> <strLocality /> <strTown>City</strTown> <strCounty /> <strPostcode>LU1 5QG</strPostcode><strDPS /></Address>")
Dim nsm = New XmlNamespaceManager(doc.NameTable)
nsm.AddNamespace("a", "http://site.co.uk/")
Dim streetValue = doc.SelectSingleNode("/a:Address/a:strStreet", nsm).InnerText
Some things to note:
For XPath lookups, if your xml has a namespace you'll need to add it to an
XmlNameSpaceManager created from your XmlDocument's NameTable.
If you don't want to
bother with that, you can walk the node collections manually via
doc.ChildNodes[0].ChildNodes[0] etc.
Or try this, which is what I believe the author was asking.
' Use XML Reader
Dim xmlDoc = New XmlDocument
Dim xmlNode As Xml.XmlNode
xmlDoc.LoadXml(strResponse)
xmlNode = xmlDoc.SelectSingleNode("//" + "strStreet")
If Not xmlNode Is Nothing Then
Dim Street = xmlNode.InnerText
End If