我想更新xml节点并搜索网站以查找this link处的示例。但是,我得到的对象引用错误未设置为对象的实例。有人会告诉我如何获取节点。提前致谢
这是我的vb代码:
Imports System.Xml
Imports System.IO
Partial Class test2
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim xmlFileNamae As String = "Vancouver.xml"
Dim xmlFilePath As String = ConfigurationManager.AppSettings("XMLFolder") & xmlFileNamae
If File.Exists(xmlFilePath) Then
Dim docXML As XmlDocument = New XmlDocument
docXML.Load(xmlFilePath)
Dim ID As String = "1"
Dim node As XmlNode = docXML.SelectSingleNode("/Orders/Order[@ID='" & ID & "']/Date")
node.InnerText = Date.Now
node = docXML.SelectSingleNode("/Orders/Order[@ID='" & ID & "']/Country")
node.InnerText = "Vancouver"
docXML.Save(xmlFilePath)
End If
End Sub
End Class
有我的xml文件:
<?xml version="1.0" encoding="utf-8"?>
<Orders>
<order ID="2">
<item>Organ</item>
<Date>7/24/2014 3:50:42 PM</Date>
<Country>China</Country>
</Order>
<order ID="1">
<item>Apple</item>
<Date>7/24/2014 3:50:42 PM</Date>
<Country>China</Country>
</order>
</Orders>
答案 0 :(得分:0)
首先,您的XML已损坏 - 您使用order
关闭了第一个Order
,这是错误的。
第二件事,你的XPath也不好。
以下是两个带有&#34;清洁工&#34;的XPath。代码。
Dim XmlDoc As New XmlDocument
Dim Node As XmlNode
XmlDoc.Load(//Your path)
//This will give you the date of the first order item in orders
//where the ID attribute equals 1.
Node = XmlDoc.SelectSingleNode("/Orders/order[@ID="1"]/Date")
//Do somehintg
//This will give you the country of the first order item in orders
//where the ID attribute equals 1.
Node=XmlDoc.SelectSingleNode("/Orders/order[@ID="1"]/Country")
//Do something else.