Reading a custom XML String with asp.NET in VB - asp.net

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...

Related

Read xml embedded in aspx page

I want to read this source as xml
http://blabla/bla.aspxPageMethod=ElencoPresentiNew&idArea=0&dtRif=&mostra=T&format=xml
That returns a result like the following (straight in the browser, not as file)
I tried to use XmlDocument or Agilitypack tool, also httpwebrequest, but I get different problems. With xmldocument I get an error saying that some xml elements are missing, with the other methods I get the html source of the page but not the data.
How can I achieve what I want? Thanks
EDIT:
first xml lines from source:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Result>
<has_custom_url>false</has_custom_url>
<oggi>24.10.2019</oggi>
<utente>
<controlli196eseguiti>true</controlli196eseguiti>
<idprofiloutente>17</idprofiloutente>
<dizionario>
<u>U</u>
<e>E</e>
</dizionario>
<nominativo>super</nominativo>
<cambiopwd>1567402823277</cambiopwd>
<descrinsediamento>Insediamento principale</descrinsediamento>
EDIT 2:
Dim doc As XmlDocument = New XmlDocument()
doc.Load("http://192.168.2.49/checkandin/area.aspx?PageMethod=ElencoPresentiNew&idArea=0&dtRif=&mostra=T&format=xml")
Dim ns As XmlNamespaceManager = New XmlNamespaceManager(doc.NameTable)
Dim nodes As XmlNodeList = doc.SelectNodes("PresentiPerAreaCalc", ns)
Dim listaIniziale As New List(Of String)
For Each node As XmlNode In nodes
Dim record As String = node.SelectSingleNode("descrazienda").Value
listaIniziale.Add(record)
Next

Populate DropDownList from HttpWebRequest XML VB.net

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

Loading xml file using asp.net return no records

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

How to parse an xml response from a post in vb.net

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

Please check my XPath query

please tell me where is problem. i wrote this xpath query but its not retriveing me any node.
i want to select "HotelName" from it:-
my selector code:
Dim xmlPath As String = Server.MapPath("aa.xml")
Dim doc As XmlDocument = New XmlDocument()
doc.Load(xmlPath)
Dim nodeList As XmlNodeList = doc.DocumentElement.SelectNodes("//HotelInfo/HotelName")
For Each child As XmlNode In nodeList
Response.Write("Node Name: " + child.Name)
Response.Write("Node Value:" + child.FirstChild.Value)
Next
my xml is like this:
<?xml version="1.0" encoding="utf-8"?>
<OTA_HotelDescriptiveInfoRS xmlns="http://www.opentravel.org/OTA/2003/05" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.opentravel.org/OTA/2003/05 OTA_HotelDescriptiveInfoRS.xsd" TimeStamp="2009-12-29T06:41:55-05:00" Version="1.006" PrimaryLangID="it" EchoToken="1" Target="Test">
<Success />
<Warnings>
<Warning Code="999" Type="2"> Your request's version is earlier than our supported version. We tried to process your request in case the versions are compatible. We support version 1.006 for the OTA_HotelDescriptiveInfoRQ call.</Warning>
</Warnings>
<HotelDescriptiveContents HotelCode="112" HotelCodeContext="HCL" HotelName="Hostal Cruz Sol" HotelCityCode="335">
<HotelDescriptiveContent HotelCode="112" HotelCodeContext="HCL" HotelName="Hostal Cruz Sol" HotelCityCode="335" CurrencyCode="EUR">
<HotelInfo>
<HotelName>Hostal Cruz Sol</HotelName>
Try this:
Dim nsmgr as XmlNamespaceManager = new XmlNamespaceManager(doc.NameTable)
nsmgr.AddNamespace("ota", "http://www.opentravel.org/OTA/2003/05")
Dim nodeList As XmlNodeList =
doc.DocumentElement.SelectNodes("//ota:HotelInfo/ota:HotelName", nsmgr)
That xmlns added a default namespace, and you need to deal with it in your XPath expression.

Resources