从xml填充组合框

时间:2015-03-20 09:09:00

标签: asp.net .net xml vb.net drop-down-menu

我想用所有付款方式填写我的下拉列表,我应该在我拥有的xml文件中找到付款方式。这应该是方法的xml代码:

    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)

stringResult给出了这个值:

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

我需要获取ddlMethod中<id></id>标签之间的值,我该怎么做?

2 个答案:

答案 0 :(得分:0)

您可以使用SelectNodes()方法从XmlDocument获取特定节点,并将合适的XPath字符串作为方法参数传递。由于SelectNodes()会返回XmlNode的集合,因此您还需要指定要在下拉列表控件中显示XmlNode的哪个属性。在这种情况下,我假设您要在<id>代码之间显示文字,以便我们使用InnerText属性:

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()

只有在你正在使用的.NET框架版本中可用时,我建议切换到XDocument,这是较旧的XmlDocument中更现代的.NET库。在各种情况下XDocument使用起来比XmlDocument更友好。使用XDocument和LINQ样式的示例:

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()

答案 1 :(得分:0)

我想出了这个,它对我有用:

 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