2014-07-24 123 views
0

我想更新xml节点并搜索该站点以找到this link处的示例。但是,我得到的对象引用错误未设置为对象的实例。有人会告诉我如何获得节点。在此先感谢无法获取特定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.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

哪一行引起错误? – Fabio

+0

你能详细说明错误在哪一行被抛出吗?在第一眼看来,我认为'xmlFilePath'没有很好地初始化'&xmlFileNamae',它可能被错写了,这会导致'.Load()'抛出错误。 –

+0

@Nadeem_MK,它抛出这一行Dim node As XmlNode = docXML.SelectSingleNode(“/ Files/File [@ ID ='”&ID&“']/Date”)。节点没有什么 – user819774

回答

0

首先,你的XML被打破 - 你关闭第一orderOrder,这是错误的。

第二件事,你的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.