【问题标题】:Cannot get the specific XML node无法获取特定的 XML 节点
【发布时间】:2014-09-16 17:21:45
【问题描述】:

我想更新 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>

【问题讨论】:

  • 哪一行引发错误?
  • 你能详细说明错误是在哪一行被抛出的吗?乍一看,我认为 xmlFilePath 没有很好地初始化 &amp; xmlFileNamae 可能写错了,这将导致 .Load() 抛出错误。
  • @Nadeem_MK ,它抛出这一行 Dim node As XmlNode = docXML.SelectSingleNode("/Files/File[@ID='" & ID & "']/Date")。节点什么都不是
  • @Fabio "Dim node As XmlNode = docXML.SelectSingleNode("/Files/File[@ID='" & ID & "']/Date")" 因为找不到节点而导致错误.谢谢

标签: xml vb.net xml-deserialization


【解决方案1】:

首先,您的 XML 已损坏 - 您将第一个 order 关闭为 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.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-29
    • 2015-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多