无法获取特定的XML节点
我想更新xml节点并搜索该站点以在中查找示例。但是,我在对象引用未设置为对象实例时遇到错误。有人能告诉我如何获取节点吗。提前谢谢 这是我的vb代码:无法获取特定的XML节点,xml,vb.net,xml-deserialization,Xml,Vb.net,Xml Deserialization,我想更新xml节点并搜索该站点以在中查找示例。但是,我在对象引用未设置为对象实例时遇到错误。有人能告诉我如何获取节点吗。提前谢谢 这是我的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
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>
首先,您的XML被破坏了——您用order关闭了第一个订单,这是错误的 第二,您的XPath也不好 这两个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.
哪一行引发错误?您能详细说明抛出错误的行吗?乍一看,我认为xmlFilePath没有很好地初始化&xmlFileNamae,这可能是写错的,这将导致.Load抛出错误。@Nadeem_MK,它在这一行中抛出Dim node作为XmlNode=docXML.SelectSingleNode/Files/File[@ID='&ID&']/Date。节点是nothing@Fabio将节点设置为XmlNode=docXML。选择singlenode/Files/File[@ID='&ID&']/Date会导致错误,因为找不到该节点。谢谢